From fe548f9bffccece67e7f0040114602d17045d4ef Mon Sep 17 00:00:00 2001 From: Sehong Na Date: Sat, 31 May 2014 13:20:13 +0900 Subject: [PATCH 1/1] Initialize Tizen 2.3 --- .gitignore | 38 ++ CMakeLists.txt | 189 ++++++ LICENSE | 203 ++++++ NOTICE | 1 + clean.sh | 38 ++ config.dtd | 25 + dir-struct.py | 111 ++++ packaging/wrt-plugins-common.spec | 109 ++++ pkgconfigs/wrt-dispatch-event.pc.in | 12 + pkgconfigs/wrt-plugin-js-overlay.pc.in | 11 + pkgconfigs/wrt-plugin-loading.pc.in | 11 + pkgconfigs/wrt-plugins-api-support.pc.in | 11 + pkgconfigs/wrt-plugins-commons-javascript.pc.in | 12 + pkgconfigs/wrt-plugins-commons.pc.in | 12 + pkgconfigs/wrt-plugins-filesystem.pc.in | 12 + pkgconfigs/wrt-plugins-ipc-message.pc.in | 12 + pkgconfigs/wrt-plugins-plugin-manager.pc.in | 12 + pkgconfigs/wrt-plugins-widget-interface.pc.in | 12 + pkgconfigs/wrt-plugins-widgetdb.pc.in | 12 + pkgconfigs/wrt-popup-ace-runner.pc.in | 12 + pkgconfigs/wrt-popup-runner.pc.in | 12 + pkgconfigs/wrt-popup-wrt-runner.pc.in | 12 + src_mobile/CMakeLists.txt | 67 ++ src_mobile/Commons/Base64.cpp | 182 ++++++ src_mobile/Commons/Base64.h | 41 ++ src_mobile/Commons/CMakeLists.txt | 106 +++ src_mobile/Commons/DESCRIPTION | 1 + src_mobile/Commons/Deprecated.h | 21 + src_mobile/Commons/Dimension.h | 72 +++ src_mobile/Commons/Emitters.h | 158 +++++ src_mobile/Commons/EventListener.h | 57 ++ src_mobile/Commons/EventReceiver.h | 319 +++++++++ src_mobile/Commons/Exception.h | 175 +++++ src_mobile/Commons/FunctionDeclaration.h | 168 +++++ src_mobile/Commons/FunctionDefinition.cpp | 34 + src_mobile/Commons/FunctionDefinition.h | 92 +++ src_mobile/Commons/IEvent.h | 383 +++++++++++ src_mobile/Commons/IExternEventCanceler.h | 48 ++ src_mobile/Commons/JSObject.cpp | 36 ++ src_mobile/Commons/JSObject.h | 52 ++ src_mobile/Commons/JSObjectDeclaration.cpp | 116 ++++ src_mobile/Commons/JSObjectDeclaration.h | 153 +++++ src_mobile/Commons/ListenerEvent.h | 131 ++++ src_mobile/Commons/ListenerEventEmitter.h | 147 +++++ src_mobile/Commons/Range.h | 49 ++ src_mobile/Commons/Regex.cpp | 53 ++ src_mobile/Commons/Regex.h | 62 ++ src_mobile/Commons/RegexPatterns.h | 30 + src_mobile/Commons/RegexUtils.cpp | 74 +++ src_mobile/Commons/RegexUtils.h | 71 ++ src_mobile/Commons/StaticAssert.h | 59 ++ src_mobile/Commons/StringBuilder.cpp | 130 ++++ src_mobile/Commons/StringBuilder.h | 48 ++ src_mobile/Commons/StringUtils.cpp | 146 +++++ src_mobile/Commons/StringUtils.h | 166 +++++ src_mobile/Commons/ThreadPool.cpp | 212 ++++++ src_mobile/Commons/ThreadPool.h | 114 ++++ src_mobile/Commons/TimeUtils.cpp | 64 ++ src_mobile/Commons/TimeUtils.h | 33 + src_mobile/Commons/TypeTraits.h | 58 ++ src_mobile/Commons/TypesDeclaration.h | 69 ++ src_mobile/Commons/WrtAccess/WrtAccess.cpp | 280 ++++++++ src_mobile/Commons/WrtAccess/WrtAccess.h | 68 ++ src_mobile/Commons/WrtAccess/config.cmake | 5 + src_mobile/Commons/plugin_initializer_def.h | 181 ++++++ src_mobile/CommonsJavaScript/CMakeLists.txt | 84 +++ src_mobile/CommonsJavaScript/Converter.cpp | 389 +++++++++++ src_mobile/CommonsJavaScript/Converter.h | 585 +++++++++++++++++ src_mobile/CommonsJavaScript/DESCRIPTION | 1 + src_mobile/CommonsJavaScript/DOMExceptionData.cpp | 36 ++ src_mobile/CommonsJavaScript/DOMExceptionData.h | 42 ++ src_mobile/CommonsJavaScript/JSCallbackManager.cpp | 241 +++++++ src_mobile/CommonsJavaScript/JSCallbackManager.h | 118 ++++ src_mobile/CommonsJavaScript/JSDOMException.cpp | 238 +++++++ src_mobile/CommonsJavaScript/JSDOMException.h | 131 ++++ .../CommonsJavaScript/JSDOMExceptionFactory.cpp | 95 +++ .../CommonsJavaScript/JSDOMExceptionFactory.h | 99 +++ .../CommonsJavaScript/JSPendingOperation.cpp | 104 +++ src_mobile/CommonsJavaScript/JSPendingOperation.h | 85 +++ .../JSPendingOperationPrivateObject.h | 115 ++++ src_mobile/CommonsJavaScript/JSUtils.cpp | 88 +++ src_mobile/CommonsJavaScript/JSUtils.h | 85 +++ src_mobile/CommonsJavaScript/PrivateObject.h | 238 +++++++ src_mobile/CommonsJavaScript/ScopedJSStringRef.cpp | 35 + src_mobile/CommonsJavaScript/ScopedJSStringRef.h | 57 ++ .../Security/SecurityFunctionDeclaration.cpp | 27 + .../Security/SecurityFunctionDeclaration.h | 96 +++ .../CommonsJavaScript/Security/StaticDeclaration.h | 315 +++++++++ src_mobile/CommonsJavaScript/SecurityExceptions.h | 73 +++ .../CommonsJavaScript/SupportPendingOperation.h | 56 ++ src_mobile/CommonsJavaScript/Utils.h | 66 ++ src_mobile/CommonsJavaScript/Validator.cpp | 131 ++++ src_mobile/CommonsJavaScript/Validator.h | 98 +++ src_mobile/DESCRIPTION | 1 + src_mobile/dispatch-event/CMakeLists.txt | 59 ++ .../dispatch-event/dispatch_event_support.cpp | 192 ++++++ src_mobile/dispatch-event/dispatch_event_support.h | 44 ++ src_mobile/js-overlay/CMakeLists.txt | 67 ++ .../JSClass/JSSoftKeyboardChangeEvent.cpp | 209 ++++++ .../deprecated/JSClass/JSSoftKeyboardChangeEvent.h | 101 +++ .../deprecated/JSClass/JSStorageEvent.cpp | 272 ++++++++ .../js-overlay/deprecated/JSClass/JSStorageEvent.h | 108 ++++ .../deprecated/JSClass/JSTizenServiceEvent.cpp | 194 ++++++ .../deprecated/JSClass/JSTizenServiceEvent.h | 94 +++ .../js-overlay/deprecated/js_iframe_support.cpp | 80 +++ .../js-overlay/deprecated/js_iframe_support.h | 68 ++ .../deprecated/js_overlay_addEventListener.cpp | 205 ++++++ .../deprecated/js_overlay_addEventListener.h | 87 +++ .../js-overlay/deprecated/js_overlay_support.cpp | 186 ++++++ .../js-overlay/deprecated/js_overlay_support.h | 40 ++ src_mobile/js-overlay/js_function_manager.cpp | 103 +++ src_mobile/js-overlay/js_function_manager.h | 55 ++ src_mobile/js-overlay/js_overlay_functions.cpp | 115 ++++ src_mobile/js-overlay/js_overlay_functions.h | 46 ++ src_mobile/js-overlay/js_overlay_types.h | 52 ++ src_mobile/modules/API/CMakeLists.txt | 22 + src_mobile/modules/API/DESCRIPTION | 2 + src_mobile/modules/API/Filesystem/Enums.h | 104 +++ src_mobile/modules/API/Filesystem/EventCopy.cpp | 63 ++ src_mobile/modules/API/Filesystem/EventCopy.h | 88 +++ src_mobile/modules/API/Filesystem/EventFind.cpp | 59 ++ src_mobile/modules/API/Filesystem/EventFind.h | 88 +++ .../modules/API/Filesystem/EventListNodes.cpp | 54 ++ src_mobile/modules/API/Filesystem/EventListNodes.h | 78 +++ src_mobile/modules/API/Filesystem/EventMove.cpp | 63 ++ src_mobile/modules/API/Filesystem/EventMove.h | 88 +++ src_mobile/modules/API/Filesystem/EventOpen.cpp | 40 ++ src_mobile/modules/API/Filesystem/EventOpen.h | 64 ++ .../modules/API/Filesystem/EventReadText.cpp | 32 + src_mobile/modules/API/Filesystem/EventReadText.h | 51 ++ src_mobile/modules/API/Filesystem/EventRemove.cpp | 45 ++ src_mobile/modules/API/Filesystem/EventRemove.h | 66 ++ src_mobile/modules/API/Filesystem/EventResolve.cpp | 40 ++ src_mobile/modules/API/Filesystem/EventResolve.h | 66 ++ src_mobile/modules/API/Filesystem/IManager.cpp | 51 ++ src_mobile/modules/API/Filesystem/IManager.h | 148 +++++ src_mobile/modules/API/Filesystem/INode.cpp | 35 + src_mobile/modules/API/Filesystem/INode.h | 185 ++++++ src_mobile/modules/API/Filesystem/INodeTypes.h | 39 ++ src_mobile/modules/API/Filesystem/IPath.cpp | 36 ++ src_mobile/modules/API/Filesystem/IPath.h | 150 +++++ src_mobile/modules/API/Filesystem/IStream.cpp | 25 + src_mobile/modules/API/Filesystem/IStream.h | 125 ++++ src_mobile/modules/API/Filesystem/NodeFilter.cpp | 111 ++++ src_mobile/modules/API/Filesystem/NodeFilter.h | 79 +++ src_mobile/modules/API/Filesystem/PathUtils.cpp | 41 ++ src_mobile/modules/API/Filesystem/PathUtils.h | 45 ++ src_mobile/modules/API/Filesystem/config.cmake | 25 + .../modules/API/LocalStorage/ILocalStorage.h | 93 +++ .../modules/API/LocalStorage/LocalStorageMgr.cpp | 36 ++ .../modules/API/LocalStorage/LocalStorageMgr.h | 37 ++ src_mobile/modules/API/LocalStorage/config.cmake | 11 + .../modules/API/Networking/EventConnected.cpp | 22 + src_mobile/modules/API/Networking/EventConnected.h | 45 ++ .../modules/API/Networking/EventDisconnected.cpp | 22 + .../modules/API/Networking/EventDisconnected.h | 46 ++ src_mobile/modules/API/Networking/IAdapter.cpp | 25 + src_mobile/modules/API/Networking/IAdapter.h | 97 +++ src_mobile/modules/API/Networking/IConnection.cpp | 25 + src_mobile/modules/API/Networking/IConnection.h | 47 ++ src_mobile/modules/API/Networking/IManager.cpp | 31 + src_mobile/modules/API/Networking/IManager.h | 56 ++ src_mobile/modules/API/Networking/config.cmake | 15 + .../modules/API/PluginManager/IPluginManager.h | 58 ++ .../API/PluginManager/PluginManagerFactory.cpp | 49 ++ .../API/PluginManager/PluginManagerFactory.h | 50 ++ src_mobile/modules/API/PluginManager/config.cmake | 11 + .../ISoftKeyboardChangeEvent.h | 47 ++ .../SoftKeyboardChangeEvent.cpp | 53 ++ .../SoftKeyboardChangeEvent.h | 55 ++ .../API/SoftKeyboardChangeEvent/config.cmake | 11 + .../modules/API/StorageEvent/IStorageEvent.h | 57 ++ .../modules/API/StorageEvent/StorageEvent.cpp | 87 +++ src_mobile/modules/API/StorageEvent/StorageEvent.h | 65 ++ .../modules/API/StorageEvent/StorageEventMgr.cpp | 36 ++ .../modules/API/StorageEvent/StorageEventMgr.h | 38 ++ src_mobile/modules/API/StorageEvent/config.cmake | 12 + .../API/TizenServiceEvent/ITizenServiceEvent.h | 49 ++ .../API/TizenServiceEvent/TizenServiceEvent.cpp | 57 ++ .../API/TizenServiceEvent/TizenServiceEvent.h | 54 ++ .../modules/API/TizenServiceEvent/config.cmake | 11 + src_mobile/modules/API/Widget/IWidget.h | 128 ++++ src_mobile/modules/API/Widget/WidgetFactory.cpp | 37 ++ src_mobile/modules/API/Widget/WidgetFactory.h | 52 ++ src_mobile/modules/API/Widget/config.cmake | 11 + src_mobile/modules/API/WidgetDB/IWidgetDB.h | 100 +++ src_mobile/modules/API/WidgetDB/IWidgetFeature.h | 49 ++ src_mobile/modules/API/WidgetDB/WidgetDBMgr.cpp | 36 ++ src_mobile/modules/API/WidgetDB/WidgetDBMgr.h | 37 ++ src_mobile/modules/API/WidgetDB/config.cmake | 12 + src_mobile/modules/API/config.cmake | 3 + src_mobile/modules/CMakeLists.txt | 22 + src_mobile/modules/DESCRIPTION | 1 + src_mobile/modules/packages/CMakeLists.txt | 34 + .../modules/packages/Filesystem/CMakeLists.txt | 54 ++ .../modules/packages/LocalStorage/CMakeLists.txt | 28 + .../modules/packages/Networking/CMakeLists.txt | 50 ++ .../modules/packages/PluginManager/CMakeLists.txt | 58 ++ .../SoftKeyboardChangeEvent/CMakeLists.txt | 26 + .../modules/packages/StorageEvent/CMakeLists.txt | 26 + .../packages/TizenServiceEvent/CMakeLists.txt | 26 + src_mobile/modules/packages/Widget/CMakeLists.txt | 30 + .../modules/packages/WidgetDB/CMakeLists.txt | 50 ++ .../packages/WidgetInterface/CMakeLists.txt | 50 ++ src_mobile/modules/tizen/CMakeLists.txt | 31 + src_mobile/modules/tizen/DESCRIPTION | 2 + src_mobile/modules/tizen/Filesystem/Manager.cpp | 623 ++++++++++++++++++ src_mobile/modules/tizen/Filesystem/Manager.h | 139 ++++ src_mobile/modules/tizen/Filesystem/Node.cpp | 608 ++++++++++++++++++ src_mobile/modules/tizen/Filesystem/Node.h | 109 ++++ .../modules/tizen/Filesystem/NodeFilterMatcher.cpp | 82 +++ .../modules/tizen/Filesystem/NodeFilterMatcher.h | 51 ++ src_mobile/modules/tizen/Filesystem/Path.cpp | 115 ++++ src_mobile/modules/tizen/Filesystem/Path.h | 65 ++ src_mobile/modules/tizen/Filesystem/Stream.cpp | 302 +++++++++ src_mobile/modules/tizen/Filesystem/Stream.h | 106 +++ src_mobile/modules/tizen/Filesystem/Utils.cpp | 100 +++ src_mobile/modules/tizen/Filesystem/Utils.h | 36 ++ src_mobile/modules/tizen/Filesystem/config.cmake | 26 + src_mobile/modules/tizen/Networking/Connection.cpp | 25 + src_mobile/modules/tizen/Networking/Connection.h | 40 ++ .../modules/tizen/Networking/EthernetAdapter.cpp | 53 ++ .../modules/tizen/Networking/EthernetAdapter.h | 68 ++ src_mobile/modules/tizen/Networking/Manager.cpp | 189 ++++++ src_mobile/modules/tizen/Networking/Manager.h | 101 +++ .../modules/tizen/Networking/WifiAdapter.cpp | 53 ++ src_mobile/modules/tizen/Networking/WifiAdapter.h | 68 ++ src_mobile/modules/tizen/Networking/config.cmake | 20 + .../modules/tizen/PluginManager/PluginManager.cpp | 265 ++++++++ .../modules/tizen/PluginManager/PluginManager.h | 66 ++ .../modules/tizen/PluginManager/config.cmake | 23 + src_mobile/modules/tizen/Widget/Property.h | 73 +++ src_mobile/modules/tizen/Widget/Widget.cpp | 175 +++++ src_mobile/modules/tizen/Widget/Widget.h | 79 +++ src_mobile/modules/tizen/Widget/config.cmake | 6 + src_mobile/modules/tizen/WidgetDB/WidgetDB.cpp | 389 +++++++++++ src_mobile/modules/tizen/WidgetDB/WidgetDB.h | 68 ++ .../modules/tizen/WidgetDB/WidgetFeature.cpp | 51 ++ src_mobile/modules/tizen/WidgetDB/WidgetFeature.h | 49 ++ src_mobile/modules/tizen/WidgetDB/config.cmake | 22 + .../modules/tizen/WidgetInterface/CMakeLists.txt | 6 + .../tizen/WidgetInterface/WidgetInterface.cpp | 139 ++++ .../tizen/WidgetInterface/WidgetInterface.h | 52 ++ .../modules/tizen/WidgetInterface/config.cmake | 17 + src_mobile/modules/tizen/config.cmake | 3 + src_mobile/plugin-loading/CMakeLists.txt | 80 +++ src_mobile/plugin-loading/explorer.cpp | 386 +++++++++++ src_mobile/plugin-loading/explorer.h | 102 +++ src_mobile/plugin-loading/javascript_interface.cpp | 431 +++++++++++++ src_mobile/plugin-loading/javascript_interface.h | 112 ++++ src_mobile/plugin-loading/js_page_session.cpp | 601 +++++++++++++++++ src_mobile/plugin-loading/js_page_session.h | 71 ++ src_mobile/plugin-loading/js_types.h | 37 ++ src_mobile/plugin-loading/plugin.cpp | 242 +++++++ src_mobile/plugin-loading/plugin.h | 92 +++ .../plugin-loading/plugin_container_support.cpp | 270 ++++++++ .../plugin-loading/plugin_container_support.h | 102 +++ .../plugin-loading/plugin_iframe_support.cpp | 77 +++ src_mobile/plugin-loading/plugin_iframe_support.h | 68 ++ src_mobile/plugin-loading/plugin_logic.cpp | 420 ++++++++++++ src_mobile/plugin-loading/plugin_logic.h | 98 +++ src_mobile/plugin-loading/plugin_model.cpp | 73 +++ src_mobile/plugin-loading/plugin_model.h | 95 +++ .../plugin-loading/plugin_property_support.cpp | 141 ++++ .../plugin-loading/plugin_property_support.h | 56 ++ src_mobile/plugins-api-support/CMakeLists.txt | 70 ++ src_mobile/plugins-api-support/CallbackSupport.h | 82 +++ src_mobile/plugins-api-support/ExportedApi.h | 150 +++++ src_mobile/plugins-api-support/IObject.h | 70 ++ src_mobile/plugins-api-support/IObject_cast.h | 35 + src_mobile/plugins-api-support/Object.cpp | 130 ++++ src_mobile/plugins-api-support/Object.h | 104 +++ src_mobile/plugins-api-support/ObjectFactory.cpp | 61 ++ src_mobile/plugins-api-support/ObjectFactory.h | 50 ++ src_mobile/plugins-api-support/Plugin.cpp | 40 ++ src_mobile/plugins-api-support/Plugin.h | 45 ++ .../plugins-api-support/PluginRegistration.cpp | 57 ++ .../plugins-api-support/PluginRegistration.h | 48 ++ .../plugins-api-support/PluginRegistrationImpl.h | 60 ++ src_mobile/plugins-api-support/PluginRegistry.cpp | 170 +++++ src_mobile/plugins-api-support/PluginRegistry.h | 80 +++ src_mobile/plugins-api-support/PluginSignals.h | 36 ++ src_mobile/plugins-api-support/SignalSignature.h | 37 ++ src_mobile/plugins-api-support/SignalsSupport.h | 98 +++ src_mobile/plugins-api-support/SoFeatures.h | 82 +++ src_mobile/plugins-api-support/detail/traits.h | 76 +++ src_mobile/plugins-api-support/js_types.h | 41 ++ src_mobile/plugins-api-support/traits.h | 41 ++ src_mobile/plugins-api-support/tuple.h | 37 ++ src_mobile/plugins-installer/CMakeLists.txt | 69 ++ src_mobile/plugins-installer/DESCRIPTION | 2 + src_mobile/plugins-installer/plugin_installer.cpp | 711 +++++++++++++++++++++ src_mobile/plugins-installer/plugin_installer.h | 96 +++ .../plugins-installer/plugin_installer_errors.h | 38 ++ .../plugins-installer/plugin_installer_types.h | 37 ++ .../plugins-installer/plugin_metafile_reader.cpp | 82 +++ .../plugins-installer/plugin_metafile_reader.h | 61 ++ src_mobile/plugins-installer/plugin_objects.cpp | 118 ++++ src_mobile/plugins-installer/plugin_objects.h | 58 ++ src_mobile/plugins-installer/plugin_utils.cpp | 89 +++ src_mobile/plugins-installer/plugin_utils.h | 35 + .../plugins-installer/wrt_plugins_installer.cpp | 46 ++ src_mobile/plugins-ipc-message/CMakeLists.txt | 60 ++ .../plugins-ipc-message/ipc_message_support.cpp | 276 ++++++++ .../plugins-ipc-message/ipc_message_support.h | 82 +++ src_mobile/standards/CMakeLists.txt | 16 + src_mobile/standards/W3C/CMakeLists.txt | 15 + src_mobile/standards/W3C/DESCRIPTION | 2 + src_mobile/standards/W3C/Widget/CMakeLists.txt | 49 ++ src_mobile/standards/W3C/Widget/JSPreferences.cpp | 528 +++++++++++++++ src_mobile/standards/W3C/Widget/JSPreferences.h | 127 ++++ src_mobile/standards/W3C/Widget/JSWidget.cpp | 560 ++++++++++++++++ src_mobile/standards/W3C/Widget/JSWidget.h | 137 ++++ src_mobile/standards/W3C/Widget/plugin_config.cpp | 40 ++ src_mobile/standards/W3C/Widget/plugin_config.h | 39 ++ .../standards/W3C/Widget/plugin_initializer.cpp | 121 ++++ src_mobile/wrt-popup/CMakeLists.txt | 2 + src_mobile/wrt-popup/ace/CMakeLists.txt | 2 + src_mobile/wrt-popup/ace/popup-bin/CMakeLists.txt | 64 ++ src_mobile/wrt-popup/ace/popup-bin/Popup.cpp | 463 ++++++++++++++ src_mobile/wrt-popup/ace/popup-bin/Popup.h | 39 ++ .../wrt-popup/ace/popup-runner/CMakeLists.txt | 65 ++ .../wrt-popup/ace/popup-runner/popup-runner.cpp | 290 +++++++++ .../wrt-popup/ace/popup-runner/popup-runner.h | 55 ++ src_mobile/wrt-popup/wrt/CMakeLists.txt | 9 + src_mobile/wrt-popup/wrt/PopupEnum.h | 29 + src_mobile/wrt-popup/wrt/PopupSerializer.cpp | 57 ++ src_mobile/wrt-popup/wrt/PopupSerializer.h | 33 + src_mobile/wrt-popup/wrt/popup-bin/CMakeLists.txt | 56 ++ src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.cpp | 77 +++ src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.h | 45 ++ .../wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp | 51 ++ .../wrt-popup/wrt/popup-bin/YesNoCheckPopup.h | 45 ++ src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.cpp | 79 +++ src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.h | 50 ++ .../wrt/popup-bin/renderer/evas_object.cpp | 234 +++++++ .../wrt-popup/wrt/popup-bin/renderer/evas_object.h | 654 +++++++++++++++++++ .../wrt-popup/wrt/popup-bin/renderer/popup.h | 70 ++ .../wrt/popup-bin/renderer/popup_controller.cpp | 111 ++++ .../wrt/popup-bin/renderer/popup_controller.h | 216 +++++++ .../wrt/popup-bin/renderer/popup_manager.cpp | 58 ++ .../wrt/popup-bin/renderer/popup_manager.h | 118 ++++ .../wrt/popup-bin/renderer/popup_object.h | 170 +++++ .../wrt/popup-bin/renderer/popup_renderer.cpp | 421 ++++++++++++ .../wrt/popup-bin/renderer/popup_renderer.h | 127 ++++ src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.cpp | 195 ++++++ src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.h | 87 +++ .../wrt-popup/wrt/popup-runner/CMakeLists.txt | 66 ++ .../wrt-popup/wrt/popup-runner/PopupInvoker.cpp | 247 +++++++ .../wrt-popup/wrt/popup-runner/PopupInvoker.h | 75 +++ src_wearable/CMakeLists.txt | 67 ++ src_wearable/Commons/Base64.cpp | 182 ++++++ src_wearable/Commons/Base64.h | 41 ++ src_wearable/Commons/CMakeLists.txt | 106 +++ src_wearable/Commons/DESCRIPTION | 1 + src_wearable/Commons/Deprecated.h | 21 + src_wearable/Commons/Dimension.h | 72 +++ src_wearable/Commons/Emitters.h | 158 +++++ src_wearable/Commons/EventListener.h | 63 ++ src_wearable/Commons/EventReceiver.h | 328 ++++++++++ src_wearable/Commons/Exception.h | 175 +++++ src_wearable/Commons/FunctionDeclaration.h | 168 +++++ src_wearable/Commons/FunctionDefinition.cpp | 34 + src_wearable/Commons/FunctionDefinition.h | 92 +++ src_wearable/Commons/IEvent.h | 383 +++++++++++ src_wearable/Commons/IExternEventCanceler.h | 55 ++ src_wearable/Commons/JSObject.cpp | 36 ++ src_wearable/Commons/JSObject.h | 52 ++ src_wearable/Commons/JSObjectDeclaration.cpp | 116 ++++ src_wearable/Commons/JSObjectDeclaration.h | 153 +++++ src_wearable/Commons/ListenerEvent.h | 131 ++++ src_wearable/Commons/ListenerEventEmitter.h | 147 +++++ src_wearable/Commons/Range.h | 49 ++ src_wearable/Commons/Regex.cpp | 53 ++ src_wearable/Commons/Regex.h | 62 ++ src_wearable/Commons/RegexPatterns.h | 30 + src_wearable/Commons/RegexUtils.cpp | 74 +++ src_wearable/Commons/RegexUtils.h | 71 ++ src_wearable/Commons/StaticAssert.h | 59 ++ src_wearable/Commons/StringBuilder.cpp | 130 ++++ src_wearable/Commons/StringBuilder.h | 48 ++ src_wearable/Commons/StringUtils.cpp | 146 +++++ src_wearable/Commons/StringUtils.h | 166 +++++ src_wearable/Commons/ThreadPool.cpp | 212 ++++++ src_wearable/Commons/ThreadPool.h | 115 ++++ src_wearable/Commons/TimeUtils.cpp | 64 ++ src_wearable/Commons/TimeUtils.h | 33 + src_wearable/Commons/TypeTraits.h | 58 ++ src_wearable/Commons/TypesDeclaration.h | 69 ++ src_wearable/Commons/WrtAccess/WrtAccess.cpp | 280 ++++++++ src_wearable/Commons/WrtAccess/WrtAccess.h | 68 ++ src_wearable/Commons/WrtAccess/config.cmake | 5 + src_wearable/Commons/plugin_initializer_def.h | 181 ++++++ src_wearable/CommonsJavaScript/CMakeLists.txt | 84 +++ src_wearable/CommonsJavaScript/Converter.cpp | 390 +++++++++++ src_wearable/CommonsJavaScript/Converter.h | 585 +++++++++++++++++ src_wearable/CommonsJavaScript/DESCRIPTION | 1 + .../CommonsJavaScript/DOMExceptionData.cpp | 36 ++ src_wearable/CommonsJavaScript/DOMExceptionData.h | 42 ++ .../CommonsJavaScript/JSCallbackManager.cpp | 247 +++++++ src_wearable/CommonsJavaScript/JSCallbackManager.h | 119 ++++ src_wearable/CommonsJavaScript/JSDOMException.cpp | 238 +++++++ src_wearable/CommonsJavaScript/JSDOMException.h | 131 ++++ .../CommonsJavaScript/JSDOMExceptionFactory.cpp | 95 +++ .../CommonsJavaScript/JSDOMExceptionFactory.h | 99 +++ .../CommonsJavaScript/JSPendingOperation.cpp | 104 +++ .../CommonsJavaScript/JSPendingOperation.h | 85 +++ .../JSPendingOperationPrivateObject.h | 115 ++++ src_wearable/CommonsJavaScript/JSUtils.cpp | 88 +++ src_wearable/CommonsJavaScript/JSUtils.h | 85 +++ src_wearable/CommonsJavaScript/PrivateObject.h | 238 +++++++ .../CommonsJavaScript/ScopedJSStringRef.cpp | 35 + src_wearable/CommonsJavaScript/ScopedJSStringRef.h | 57 ++ .../Security/SecurityFunctionDeclaration.cpp | 27 + .../Security/SecurityFunctionDeclaration.h | 96 +++ .../CommonsJavaScript/Security/StaticDeclaration.h | 315 +++++++++ .../CommonsJavaScript/SecurityExceptions.h | 73 +++ .../CommonsJavaScript/SupportPendingOperation.h | 56 ++ src_wearable/CommonsJavaScript/Utils.h | 66 ++ src_wearable/CommonsJavaScript/Validator.cpp | 131 ++++ src_wearable/CommonsJavaScript/Validator.h | 98 +++ src_wearable/DESCRIPTION | 1 + src_wearable/dispatch-event/CMakeLists.txt | 59 ++ .../dispatch-event/dispatch_event_support.cpp | 217 +++++++ .../dispatch-event/dispatch_event_support.h | 45 ++ src_wearable/js-overlay/CMakeLists.txt | 67 ++ .../JSClass/JSSoftKeyboardChangeEvent.cpp | 209 ++++++ .../deprecated/JSClass/JSSoftKeyboardChangeEvent.h | 101 +++ .../deprecated/JSClass/JSStorageEvent.cpp | 272 ++++++++ .../js-overlay/deprecated/JSClass/JSStorageEvent.h | 108 ++++ .../deprecated/JSClass/JSTizenServiceEvent.cpp | 194 ++++++ .../deprecated/JSClass/JSTizenServiceEvent.h | 94 +++ .../js-overlay/deprecated/js_iframe_support.cpp | 80 +++ .../js-overlay/deprecated/js_iframe_support.h | 68 ++ .../deprecated/js_overlay_addEventListener.cpp | 205 ++++++ .../deprecated/js_overlay_addEventListener.h | 87 +++ .../js-overlay/deprecated/js_overlay_support.cpp | 186 ++++++ .../js-overlay/deprecated/js_overlay_support.h | 40 ++ src_wearable/js-overlay/js_function_manager.cpp | 103 +++ src_wearable/js-overlay/js_function_manager.h | 55 ++ src_wearable/js-overlay/js_overlay_functions.cpp | 115 ++++ src_wearable/js-overlay/js_overlay_functions.h | 46 ++ src_wearable/js-overlay/js_overlay_types.h | 52 ++ src_wearable/modules/API/CMakeLists.txt | 22 + src_wearable/modules/API/DESCRIPTION | 2 + src_wearable/modules/API/Filesystem/Enums.h | 104 +++ src_wearable/modules/API/Filesystem/EventCopy.cpp | 63 ++ src_wearable/modules/API/Filesystem/EventCopy.h | 88 +++ src_wearable/modules/API/Filesystem/EventFind.cpp | 59 ++ src_wearable/modules/API/Filesystem/EventFind.h | 88 +++ .../modules/API/Filesystem/EventListNodes.cpp | 54 ++ .../modules/API/Filesystem/EventListNodes.h | 78 +++ src_wearable/modules/API/Filesystem/EventMove.cpp | 63 ++ src_wearable/modules/API/Filesystem/EventMove.h | 88 +++ src_wearable/modules/API/Filesystem/EventOpen.cpp | 40 ++ src_wearable/modules/API/Filesystem/EventOpen.h | 64 ++ .../modules/API/Filesystem/EventReadText.cpp | 32 + .../modules/API/Filesystem/EventReadText.h | 51 ++ .../modules/API/Filesystem/EventRemove.cpp | 45 ++ src_wearable/modules/API/Filesystem/EventRemove.h | 66 ++ .../modules/API/Filesystem/EventResolve.cpp | 40 ++ src_wearable/modules/API/Filesystem/EventResolve.h | 66 ++ src_wearable/modules/API/Filesystem/IManager.cpp | 51 ++ src_wearable/modules/API/Filesystem/IManager.h | 148 +++++ src_wearable/modules/API/Filesystem/INode.cpp | 35 + src_wearable/modules/API/Filesystem/INode.h | 185 ++++++ src_wearable/modules/API/Filesystem/INodeTypes.h | 39 ++ src_wearable/modules/API/Filesystem/IPath.cpp | 36 ++ src_wearable/modules/API/Filesystem/IPath.h | 150 +++++ src_wearable/modules/API/Filesystem/IStream.cpp | 25 + src_wearable/modules/API/Filesystem/IStream.h | 125 ++++ src_wearable/modules/API/Filesystem/NodeFilter.cpp | 111 ++++ src_wearable/modules/API/Filesystem/NodeFilter.h | 79 +++ src_wearable/modules/API/Filesystem/PathUtils.cpp | 41 ++ src_wearable/modules/API/Filesystem/PathUtils.h | 45 ++ src_wearable/modules/API/Filesystem/config.cmake | 25 + .../modules/API/LocalStorage/ILocalStorage.h | 93 +++ .../modules/API/LocalStorage/LocalStorageMgr.cpp | 36 ++ .../modules/API/LocalStorage/LocalStorageMgr.h | 37 ++ src_wearable/modules/API/LocalStorage/config.cmake | 11 + .../modules/API/PluginManager/IPluginManager.h | 58 ++ .../API/PluginManager/PluginManagerFactory.cpp | 49 ++ .../API/PluginManager/PluginManagerFactory.h | 50 ++ .../modules/API/PluginManager/config.cmake | 11 + .../ISoftKeyboardChangeEvent.h | 47 ++ .../SoftKeyboardChangeEvent.cpp | 53 ++ .../SoftKeyboardChangeEvent.h | 55 ++ .../API/SoftKeyboardChangeEvent/config.cmake | 11 + .../modules/API/StorageEvent/IStorageEvent.h | 57 ++ .../modules/API/StorageEvent/StorageEvent.cpp | 87 +++ .../modules/API/StorageEvent/StorageEvent.h | 65 ++ .../modules/API/StorageEvent/StorageEventMgr.cpp | 36 ++ .../modules/API/StorageEvent/StorageEventMgr.h | 38 ++ src_wearable/modules/API/StorageEvent/config.cmake | 12 + .../API/TizenServiceEvent/ITizenServiceEvent.h | 49 ++ .../API/TizenServiceEvent/TizenServiceEvent.cpp | 57 ++ .../API/TizenServiceEvent/TizenServiceEvent.h | 54 ++ .../modules/API/TizenServiceEvent/config.cmake | 11 + src_wearable/modules/API/Widget/IWidget.h | 128 ++++ src_wearable/modules/API/Widget/WidgetFactory.cpp | 37 ++ src_wearable/modules/API/Widget/WidgetFactory.h | 52 ++ src_wearable/modules/API/Widget/config.cmake | 11 + src_wearable/modules/API/WidgetDB/IWidgetDB.h | 99 +++ src_wearable/modules/API/WidgetDB/IWidgetFeature.h | 49 ++ src_wearable/modules/API/WidgetDB/WidgetDBMgr.cpp | 36 ++ src_wearable/modules/API/WidgetDB/WidgetDBMgr.h | 37 ++ src_wearable/modules/API/WidgetDB/config.cmake | 12 + src_wearable/modules/API/config.cmake | 3 + src_wearable/modules/CMakeLists.txt | 22 + src_wearable/modules/DESCRIPTION | 1 + src_wearable/modules/packages/CMakeLists.txt | 34 + .../modules/packages/Filesystem/CMakeLists.txt | 54 ++ .../modules/packages/LocalStorage/CMakeLists.txt | 28 + .../modules/packages/PluginManager/CMakeLists.txt | 58 ++ .../SoftKeyboardChangeEvent/CMakeLists.txt | 26 + .../modules/packages/StorageEvent/CMakeLists.txt | 26 + .../packages/TizenServiceEvent/CMakeLists.txt | 26 + .../modules/packages/Widget/CMakeLists.txt | 30 + .../modules/packages/WidgetDB/CMakeLists.txt | 50 ++ .../packages/WidgetInterface/CMakeLists.txt | 50 ++ src_wearable/modules/tizen/CMakeLists.txt | 31 + src_wearable/modules/tizen/DESCRIPTION | 2 + src_wearable/modules/tizen/Filesystem/Manager.cpp | 623 ++++++++++++++++++ src_wearable/modules/tizen/Filesystem/Manager.h | 139 ++++ src_wearable/modules/tizen/Filesystem/Node.cpp | 608 ++++++++++++++++++ src_wearable/modules/tizen/Filesystem/Node.h | 109 ++++ .../modules/tizen/Filesystem/NodeFilterMatcher.cpp | 82 +++ .../modules/tizen/Filesystem/NodeFilterMatcher.h | 51 ++ src_wearable/modules/tizen/Filesystem/Path.cpp | 115 ++++ src_wearable/modules/tizen/Filesystem/Path.h | 65 ++ src_wearable/modules/tizen/Filesystem/Stream.cpp | 302 +++++++++ src_wearable/modules/tizen/Filesystem/Stream.h | 106 +++ src_wearable/modules/tizen/Filesystem/Utils.cpp | 100 +++ src_wearable/modules/tizen/Filesystem/Utils.h | 36 ++ src_wearable/modules/tizen/Filesystem/config.cmake | 26 + .../modules/tizen/PluginManager/PluginManager.cpp | 265 ++++++++ .../modules/tizen/PluginManager/PluginManager.h | 66 ++ .../modules/tizen/PluginManager/config.cmake | 23 + src_wearable/modules/tizen/Widget/Property.h | 73 +++ src_wearable/modules/tizen/Widget/Widget.cpp | 175 +++++ src_wearable/modules/tizen/Widget/Widget.h | 79 +++ src_wearable/modules/tizen/Widget/config.cmake | 6 + src_wearable/modules/tizen/WidgetDB/WidgetDB.cpp | 385 +++++++++++ src_wearable/modules/tizen/WidgetDB/WidgetDB.h | 68 ++ .../modules/tizen/WidgetDB/WidgetFeature.cpp | 51 ++ .../modules/tizen/WidgetDB/WidgetFeature.h | 49 ++ src_wearable/modules/tizen/WidgetDB/config.cmake | 22 + .../modules/tizen/WidgetInterface/CMakeLists.txt | 6 + .../tizen/WidgetInterface/WidgetInterface.cpp | 138 ++++ .../tizen/WidgetInterface/WidgetInterface.h | 52 ++ .../modules/tizen/WidgetInterface/config.cmake | 17 + src_wearable/modules/tizen/config.cmake | 3 + src_wearable/plugin-loading/CMakeLists.txt | 80 +++ src_wearable/plugin-loading/explorer.cpp | 386 +++++++++++ src_wearable/plugin-loading/explorer.h | 102 +++ .../plugin-loading/javascript_interface.cpp | 431 +++++++++++++ src_wearable/plugin-loading/javascript_interface.h | 112 ++++ src_wearable/plugin-loading/js_page_session.cpp | 600 +++++++++++++++++ src_wearable/plugin-loading/js_page_session.h | 71 ++ src_wearable/plugin-loading/js_types.h | 37 ++ src_wearable/plugin-loading/plugin.cpp | 242 +++++++ src_wearable/plugin-loading/plugin.h | 92 +++ .../plugin-loading/plugin_container_support.cpp | 270 ++++++++ .../plugin-loading/plugin_container_support.h | 102 +++ .../plugin-loading/plugin_iframe_support.cpp | 77 +++ .../plugin-loading/plugin_iframe_support.h | 68 ++ src_wearable/plugin-loading/plugin_logic.cpp | 420 ++++++++++++ src_wearable/plugin-loading/plugin_logic.h | 98 +++ src_wearable/plugin-loading/plugin_model.cpp | 73 +++ src_wearable/plugin-loading/plugin_model.h | 95 +++ .../plugin-loading/plugin_property_support.cpp | 141 ++++ .../plugin-loading/plugin_property_support.h | 56 ++ src_wearable/plugins-api-support/CMakeLists.txt | 70 ++ src_wearable/plugins-api-support/CallbackSupport.h | 82 +++ src_wearable/plugins-api-support/ExportedApi.h | 150 +++++ src_wearable/plugins-api-support/IObject.h | 70 ++ src_wearable/plugins-api-support/IObject_cast.h | 35 + src_wearable/plugins-api-support/Object.cpp | 130 ++++ src_wearable/plugins-api-support/Object.h | 104 +++ src_wearable/plugins-api-support/ObjectFactory.cpp | 61 ++ src_wearable/plugins-api-support/ObjectFactory.h | 50 ++ src_wearable/plugins-api-support/Plugin.cpp | 40 ++ src_wearable/plugins-api-support/Plugin.h | 45 ++ .../plugins-api-support/PluginRegistration.cpp | 57 ++ .../plugins-api-support/PluginRegistration.h | 48 ++ .../plugins-api-support/PluginRegistrationImpl.h | 60 ++ .../plugins-api-support/PluginRegistry.cpp | 170 +++++ src_wearable/plugins-api-support/PluginRegistry.h | 80 +++ src_wearable/plugins-api-support/PluginSignals.h | 36 ++ src_wearable/plugins-api-support/SignalSignature.h | 37 ++ src_wearable/plugins-api-support/SignalsSupport.h | 98 +++ src_wearable/plugins-api-support/detail/traits.h | 76 +++ src_wearable/plugins-api-support/js_types.h | 41 ++ src_wearable/plugins-api-support/traits.h | 41 ++ src_wearable/plugins-api-support/tuple.h | 37 ++ src_wearable/plugins-installer/CMakeLists.txt | 69 ++ src_wearable/plugins-installer/DESCRIPTION | 2 + .../plugins-installer/plugin_installer.cpp | 710 ++++++++++++++++++++ src_wearable/plugins-installer/plugin_installer.h | 97 +++ .../plugins-installer/plugin_installer_errors.h | 38 ++ .../plugins-installer/plugin_installer_types.h | 37 ++ .../plugins-installer/plugin_metafile_reader.cpp | 82 +++ .../plugins-installer/plugin_metafile_reader.h | 61 ++ src_wearable/plugins-installer/plugin_objects.cpp | 118 ++++ src_wearable/plugins-installer/plugin_objects.h | 58 ++ src_wearable/plugins-installer/plugin_utils.cpp | 89 +++ src_wearable/plugins-installer/plugin_utils.h | 35 + .../plugins-installer/wrt_plugins_installer.cpp | 46 ++ src_wearable/plugins-ipc-message/CMakeLists.txt | 60 ++ .../plugins-ipc-message/ipc_message_support.cpp | 240 +++++++ .../plugins-ipc-message/ipc_message_support.h | 82 +++ src_wearable/standards/CMakeLists.txt | 16 + src_wearable/standards/W3C/CMakeLists.txt | 15 + src_wearable/standards/W3C/DESCRIPTION | 2 + src_wearable/standards/W3C/Widget/CMakeLists.txt | 51 ++ .../standards/W3C/Widget/JSPreferences.cpp | 528 +++++++++++++++ src_wearable/standards/W3C/Widget/JSPreferences.h | 127 ++++ src_wearable/standards/W3C/Widget/JSWidget.cpp | 561 ++++++++++++++++ src_wearable/standards/W3C/Widget/JSWidget.h | 137 ++++ .../standards/W3C/Widget/plugin_config.cpp | 40 ++ src_wearable/standards/W3C/Widget/plugin_config.h | 39 ++ .../standards/W3C/Widget/plugin_initializer.cpp | 160 +++++ src_wearable/wrt-popup/CMakeLists.txt | 2 + src_wearable/wrt-popup/ace/CMakeLists.txt | 2 + .../wrt-popup/ace/popup-bin/CMakeLists.txt | 64 ++ src_wearable/wrt-popup/ace/popup-bin/Popup.cpp | 465 ++++++++++++++ src_wearable/wrt-popup/ace/popup-bin/Popup.h | 39 ++ .../wrt-popup/ace/popup-runner/CMakeLists.txt | 65 ++ .../wrt-popup/ace/popup-runner/popup-runner.cpp | 290 +++++++++ .../wrt-popup/ace/popup-runner/popup-runner.h | 55 ++ src_wearable/wrt-popup/wrt/CMakeLists.txt | 9 + src_wearable/wrt-popup/wrt/PopupEnum.h | 29 + src_wearable/wrt-popup/wrt/PopupSerializer.cpp | 57 ++ src_wearable/wrt-popup/wrt/PopupSerializer.h | 33 + .../wrt-popup/wrt/popup-bin/CMakeLists.txt | 56 ++ src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.cpp | 77 +++ src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.h | 45 ++ .../wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp | 51 ++ .../wrt-popup/wrt/popup-bin/YesNoCheckPopup.h | 45 ++ .../wrt-popup/wrt/popup-bin/YesNoPopup.cpp | 79 +++ src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.h | 50 ++ .../wrt/popup-bin/renderer/evas_object.cpp | 234 +++++++ .../wrt-popup/wrt/popup-bin/renderer/evas_object.h | 654 +++++++++++++++++++ .../wrt-popup/wrt/popup-bin/renderer/popup.h | 70 ++ .../wrt/popup-bin/renderer/popup_controller.cpp | 111 ++++ .../wrt/popup-bin/renderer/popup_controller.h | 216 +++++++ .../wrt/popup-bin/renderer/popup_manager.cpp | 58 ++ .../wrt/popup-bin/renderer/popup_manager.h | 117 ++++ .../wrt/popup-bin/renderer/popup_object.h | 170 +++++ .../wrt/popup-bin/renderer/popup_renderer.cpp | 424 ++++++++++++ .../wrt/popup-bin/renderer/popup_renderer.h | 127 ++++ src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.cpp | 195 ++++++ src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.h | 87 +++ .../wrt-popup/wrt/popup-runner/CMakeLists.txt | 66 ++ .../wrt-popup/wrt/popup-runner/PopupInvoker.cpp | 247 +++++++ .../wrt-popup/wrt/popup-runner/PopupInvoker.h | 75 +++ tests/CMakeLists.txt | 21 + tests/CMakeUtils.txt | 69 ++ tests/dao/CMakeLists.txt | 47 ++ tests/dao/README | 12 + tests/dao/TestInit.cpp | 62 ++ tests/dao/WidgetDBTest.cpp | 422 ++++++++++++ tests/dao/widgetdb_tests_prepare_db.sh | 122 ++++ uncrustify.cfg | 170 +++++ uncrustify.sh | 1 + wrt-plugins-common.manifest | 13 + wrt-plugins-common.map | 6 + wrt-popup-ace-runtime.mobile.rule | 14 + wrt-popup-ace-runtime.mobile2.rule | 13 + wrt-popup-ace-runtime.rule | 13 + wrt-popup-wrt-runtime.mobile.rule | 14 + wrt-popup-wrt-runtime.mobile2.rule | 13 + wrt-popup-wrt-runtime.rule | 13 + 673 files changed, 66336 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 LICENSE create mode 100644 NOTICE create mode 100755 clean.sh create mode 100644 config.dtd create mode 100755 dir-struct.py create mode 100644 packaging/wrt-plugins-common.spec create mode 100644 pkgconfigs/wrt-dispatch-event.pc.in create mode 100644 pkgconfigs/wrt-plugin-js-overlay.pc.in create mode 100644 pkgconfigs/wrt-plugin-loading.pc.in create mode 100644 pkgconfigs/wrt-plugins-api-support.pc.in create mode 100644 pkgconfigs/wrt-plugins-commons-javascript.pc.in create mode 100644 pkgconfigs/wrt-plugins-commons.pc.in create mode 100644 pkgconfigs/wrt-plugins-filesystem.pc.in create mode 100644 pkgconfigs/wrt-plugins-ipc-message.pc.in create mode 100644 pkgconfigs/wrt-plugins-plugin-manager.pc.in create mode 100644 pkgconfigs/wrt-plugins-widget-interface.pc.in create mode 100644 pkgconfigs/wrt-plugins-widgetdb.pc.in create mode 100644 pkgconfigs/wrt-popup-ace-runner.pc.in create mode 100644 pkgconfigs/wrt-popup-runner.pc.in create mode 100644 pkgconfigs/wrt-popup-wrt-runner.pc.in create mode 100644 src_mobile/CMakeLists.txt create mode 100644 src_mobile/Commons/Base64.cpp create mode 100644 src_mobile/Commons/Base64.h create mode 100644 src_mobile/Commons/CMakeLists.txt create mode 100644 src_mobile/Commons/DESCRIPTION create mode 100644 src_mobile/Commons/Deprecated.h create mode 100644 src_mobile/Commons/Dimension.h create mode 100644 src_mobile/Commons/Emitters.h create mode 100644 src_mobile/Commons/EventListener.h create mode 100644 src_mobile/Commons/EventReceiver.h create mode 100644 src_mobile/Commons/Exception.h create mode 100644 src_mobile/Commons/FunctionDeclaration.h create mode 100644 src_mobile/Commons/FunctionDefinition.cpp create mode 100644 src_mobile/Commons/FunctionDefinition.h create mode 100644 src_mobile/Commons/IEvent.h create mode 100644 src_mobile/Commons/IExternEventCanceler.h create mode 100644 src_mobile/Commons/JSObject.cpp create mode 100644 src_mobile/Commons/JSObject.h create mode 100755 src_mobile/Commons/JSObjectDeclaration.cpp create mode 100644 src_mobile/Commons/JSObjectDeclaration.h create mode 100644 src_mobile/Commons/ListenerEvent.h create mode 100644 src_mobile/Commons/ListenerEventEmitter.h create mode 100644 src_mobile/Commons/Range.h create mode 100644 src_mobile/Commons/Regex.cpp create mode 100644 src_mobile/Commons/Regex.h create mode 100644 src_mobile/Commons/RegexPatterns.h create mode 100644 src_mobile/Commons/RegexUtils.cpp create mode 100644 src_mobile/Commons/RegexUtils.h create mode 100644 src_mobile/Commons/StaticAssert.h create mode 100644 src_mobile/Commons/StringBuilder.cpp create mode 100644 src_mobile/Commons/StringBuilder.h create mode 100644 src_mobile/Commons/StringUtils.cpp create mode 100644 src_mobile/Commons/StringUtils.h create mode 100644 src_mobile/Commons/ThreadPool.cpp create mode 100644 src_mobile/Commons/ThreadPool.h create mode 100644 src_mobile/Commons/TimeUtils.cpp create mode 100644 src_mobile/Commons/TimeUtils.h create mode 100644 src_mobile/Commons/TypeTraits.h create mode 100644 src_mobile/Commons/TypesDeclaration.h create mode 100644 src_mobile/Commons/WrtAccess/WrtAccess.cpp create mode 100644 src_mobile/Commons/WrtAccess/WrtAccess.h create mode 100644 src_mobile/Commons/WrtAccess/config.cmake create mode 100644 src_mobile/Commons/plugin_initializer_def.h create mode 100755 src_mobile/CommonsJavaScript/CMakeLists.txt create mode 100644 src_mobile/CommonsJavaScript/Converter.cpp create mode 100644 src_mobile/CommonsJavaScript/Converter.h create mode 100644 src_mobile/CommonsJavaScript/DESCRIPTION create mode 100644 src_mobile/CommonsJavaScript/DOMExceptionData.cpp create mode 100644 src_mobile/CommonsJavaScript/DOMExceptionData.h create mode 100644 src_mobile/CommonsJavaScript/JSCallbackManager.cpp create mode 100644 src_mobile/CommonsJavaScript/JSCallbackManager.h create mode 100644 src_mobile/CommonsJavaScript/JSDOMException.cpp create mode 100644 src_mobile/CommonsJavaScript/JSDOMException.h create mode 100644 src_mobile/CommonsJavaScript/JSDOMExceptionFactory.cpp create mode 100644 src_mobile/CommonsJavaScript/JSDOMExceptionFactory.h create mode 100644 src_mobile/CommonsJavaScript/JSPendingOperation.cpp create mode 100644 src_mobile/CommonsJavaScript/JSPendingOperation.h create mode 100644 src_mobile/CommonsJavaScript/JSPendingOperationPrivateObject.h create mode 100644 src_mobile/CommonsJavaScript/JSUtils.cpp create mode 100644 src_mobile/CommonsJavaScript/JSUtils.h create mode 100644 src_mobile/CommonsJavaScript/PrivateObject.h create mode 100644 src_mobile/CommonsJavaScript/ScopedJSStringRef.cpp create mode 100644 src_mobile/CommonsJavaScript/ScopedJSStringRef.h create mode 100644 src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp create mode 100644 src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.h create mode 100644 src_mobile/CommonsJavaScript/Security/StaticDeclaration.h create mode 100644 src_mobile/CommonsJavaScript/SecurityExceptions.h create mode 100644 src_mobile/CommonsJavaScript/SupportPendingOperation.h create mode 100644 src_mobile/CommonsJavaScript/Utils.h create mode 100644 src_mobile/CommonsJavaScript/Validator.cpp create mode 100644 src_mobile/CommonsJavaScript/Validator.h create mode 100644 src_mobile/DESCRIPTION create mode 100644 src_mobile/dispatch-event/CMakeLists.txt create mode 100755 src_mobile/dispatch-event/dispatch_event_support.cpp create mode 100644 src_mobile/dispatch-event/dispatch_event_support.h create mode 100644 src_mobile/js-overlay/CMakeLists.txt create mode 100644 src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp create mode 100644 src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h create mode 100644 src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.cpp create mode 100644 src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.h create mode 100644 src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp create mode 100644 src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h create mode 100755 src_mobile/js-overlay/deprecated/js_iframe_support.cpp create mode 100755 src_mobile/js-overlay/deprecated/js_iframe_support.h create mode 100755 src_mobile/js-overlay/deprecated/js_overlay_addEventListener.cpp create mode 100755 src_mobile/js-overlay/deprecated/js_overlay_addEventListener.h create mode 100644 src_mobile/js-overlay/deprecated/js_overlay_support.cpp create mode 100644 src_mobile/js-overlay/deprecated/js_overlay_support.h create mode 100644 src_mobile/js-overlay/js_function_manager.cpp create mode 100644 src_mobile/js-overlay/js_function_manager.h create mode 100644 src_mobile/js-overlay/js_overlay_functions.cpp create mode 100644 src_mobile/js-overlay/js_overlay_functions.h create mode 100644 src_mobile/js-overlay/js_overlay_types.h create mode 100644 src_mobile/modules/API/CMakeLists.txt create mode 100644 src_mobile/modules/API/DESCRIPTION create mode 100644 src_mobile/modules/API/Filesystem/Enums.h create mode 100644 src_mobile/modules/API/Filesystem/EventCopy.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventCopy.h create mode 100644 src_mobile/modules/API/Filesystem/EventFind.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventFind.h create mode 100644 src_mobile/modules/API/Filesystem/EventListNodes.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventListNodes.h create mode 100644 src_mobile/modules/API/Filesystem/EventMove.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventMove.h create mode 100644 src_mobile/modules/API/Filesystem/EventOpen.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventOpen.h create mode 100644 src_mobile/modules/API/Filesystem/EventReadText.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventReadText.h create mode 100644 src_mobile/modules/API/Filesystem/EventRemove.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventRemove.h create mode 100644 src_mobile/modules/API/Filesystem/EventResolve.cpp create mode 100644 src_mobile/modules/API/Filesystem/EventResolve.h create mode 100644 src_mobile/modules/API/Filesystem/IManager.cpp create mode 100644 src_mobile/modules/API/Filesystem/IManager.h create mode 100644 src_mobile/modules/API/Filesystem/INode.cpp create mode 100644 src_mobile/modules/API/Filesystem/INode.h create mode 100644 src_mobile/modules/API/Filesystem/INodeTypes.h create mode 100644 src_mobile/modules/API/Filesystem/IPath.cpp create mode 100644 src_mobile/modules/API/Filesystem/IPath.h create mode 100644 src_mobile/modules/API/Filesystem/IStream.cpp create mode 100644 src_mobile/modules/API/Filesystem/IStream.h create mode 100644 src_mobile/modules/API/Filesystem/NodeFilter.cpp create mode 100644 src_mobile/modules/API/Filesystem/NodeFilter.h create mode 100644 src_mobile/modules/API/Filesystem/PathUtils.cpp create mode 100644 src_mobile/modules/API/Filesystem/PathUtils.h create mode 100644 src_mobile/modules/API/Filesystem/config.cmake create mode 100644 src_mobile/modules/API/LocalStorage/ILocalStorage.h create mode 100644 src_mobile/modules/API/LocalStorage/LocalStorageMgr.cpp create mode 100644 src_mobile/modules/API/LocalStorage/LocalStorageMgr.h create mode 100644 src_mobile/modules/API/LocalStorage/config.cmake create mode 100644 src_mobile/modules/API/Networking/EventConnected.cpp create mode 100644 src_mobile/modules/API/Networking/EventConnected.h create mode 100644 src_mobile/modules/API/Networking/EventDisconnected.cpp create mode 100644 src_mobile/modules/API/Networking/EventDisconnected.h create mode 100644 src_mobile/modules/API/Networking/IAdapter.cpp create mode 100644 src_mobile/modules/API/Networking/IAdapter.h create mode 100644 src_mobile/modules/API/Networking/IConnection.cpp create mode 100644 src_mobile/modules/API/Networking/IConnection.h create mode 100644 src_mobile/modules/API/Networking/IManager.cpp create mode 100644 src_mobile/modules/API/Networking/IManager.h create mode 100644 src_mobile/modules/API/Networking/config.cmake create mode 100644 src_mobile/modules/API/PluginManager/IPluginManager.h create mode 100644 src_mobile/modules/API/PluginManager/PluginManagerFactory.cpp create mode 100644 src_mobile/modules/API/PluginManager/PluginManagerFactory.h create mode 100644 src_mobile/modules/API/PluginManager/config.cmake create mode 100644 src_mobile/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h create mode 100644 src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp create mode 100644 src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h create mode 100644 src_mobile/modules/API/SoftKeyboardChangeEvent/config.cmake create mode 100644 src_mobile/modules/API/StorageEvent/IStorageEvent.h create mode 100644 src_mobile/modules/API/StorageEvent/StorageEvent.cpp create mode 100644 src_mobile/modules/API/StorageEvent/StorageEvent.h create mode 100644 src_mobile/modules/API/StorageEvent/StorageEventMgr.cpp create mode 100644 src_mobile/modules/API/StorageEvent/StorageEventMgr.h create mode 100644 src_mobile/modules/API/StorageEvent/config.cmake create mode 100644 src_mobile/modules/API/TizenServiceEvent/ITizenServiceEvent.h create mode 100644 src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.cpp create mode 100644 src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.h create mode 100644 src_mobile/modules/API/TizenServiceEvent/config.cmake create mode 100644 src_mobile/modules/API/Widget/IWidget.h create mode 100644 src_mobile/modules/API/Widget/WidgetFactory.cpp create mode 100644 src_mobile/modules/API/Widget/WidgetFactory.h create mode 100644 src_mobile/modules/API/Widget/config.cmake create mode 100644 src_mobile/modules/API/WidgetDB/IWidgetDB.h create mode 100644 src_mobile/modules/API/WidgetDB/IWidgetFeature.h create mode 100644 src_mobile/modules/API/WidgetDB/WidgetDBMgr.cpp create mode 100644 src_mobile/modules/API/WidgetDB/WidgetDBMgr.h create mode 100644 src_mobile/modules/API/WidgetDB/config.cmake create mode 100644 src_mobile/modules/API/config.cmake create mode 100644 src_mobile/modules/CMakeLists.txt create mode 100644 src_mobile/modules/DESCRIPTION create mode 100644 src_mobile/modules/packages/CMakeLists.txt create mode 100644 src_mobile/modules/packages/Filesystem/CMakeLists.txt create mode 100644 src_mobile/modules/packages/LocalStorage/CMakeLists.txt create mode 100644 src_mobile/modules/packages/Networking/CMakeLists.txt create mode 100644 src_mobile/modules/packages/PluginManager/CMakeLists.txt create mode 100644 src_mobile/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt create mode 100644 src_mobile/modules/packages/StorageEvent/CMakeLists.txt create mode 100644 src_mobile/modules/packages/TizenServiceEvent/CMakeLists.txt create mode 100644 src_mobile/modules/packages/Widget/CMakeLists.txt create mode 100644 src_mobile/modules/packages/WidgetDB/CMakeLists.txt create mode 100644 src_mobile/modules/packages/WidgetInterface/CMakeLists.txt create mode 100644 src_mobile/modules/tizen/CMakeLists.txt create mode 100644 src_mobile/modules/tizen/DESCRIPTION create mode 100644 src_mobile/modules/tizen/Filesystem/Manager.cpp create mode 100644 src_mobile/modules/tizen/Filesystem/Manager.h create mode 100644 src_mobile/modules/tizen/Filesystem/Node.cpp create mode 100644 src_mobile/modules/tizen/Filesystem/Node.h create mode 100644 src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.cpp create mode 100644 src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.h create mode 100644 src_mobile/modules/tizen/Filesystem/Path.cpp create mode 100644 src_mobile/modules/tizen/Filesystem/Path.h create mode 100644 src_mobile/modules/tizen/Filesystem/Stream.cpp create mode 100644 src_mobile/modules/tizen/Filesystem/Stream.h create mode 100644 src_mobile/modules/tizen/Filesystem/Utils.cpp create mode 100644 src_mobile/modules/tizen/Filesystem/Utils.h create mode 100644 src_mobile/modules/tizen/Filesystem/config.cmake create mode 100644 src_mobile/modules/tizen/Networking/Connection.cpp create mode 100644 src_mobile/modules/tizen/Networking/Connection.h create mode 100644 src_mobile/modules/tizen/Networking/EthernetAdapter.cpp create mode 100644 src_mobile/modules/tizen/Networking/EthernetAdapter.h create mode 100644 src_mobile/modules/tizen/Networking/Manager.cpp create mode 100644 src_mobile/modules/tizen/Networking/Manager.h create mode 100644 src_mobile/modules/tizen/Networking/WifiAdapter.cpp create mode 100644 src_mobile/modules/tizen/Networking/WifiAdapter.h create mode 100644 src_mobile/modules/tizen/Networking/config.cmake create mode 100644 src_mobile/modules/tizen/PluginManager/PluginManager.cpp create mode 100644 src_mobile/modules/tizen/PluginManager/PluginManager.h create mode 100644 src_mobile/modules/tizen/PluginManager/config.cmake create mode 100644 src_mobile/modules/tizen/Widget/Property.h create mode 100644 src_mobile/modules/tizen/Widget/Widget.cpp create mode 100644 src_mobile/modules/tizen/Widget/Widget.h create mode 100644 src_mobile/modules/tizen/Widget/config.cmake create mode 100644 src_mobile/modules/tizen/WidgetDB/WidgetDB.cpp create mode 100644 src_mobile/modules/tizen/WidgetDB/WidgetDB.h create mode 100644 src_mobile/modules/tizen/WidgetDB/WidgetFeature.cpp create mode 100644 src_mobile/modules/tizen/WidgetDB/WidgetFeature.h create mode 100644 src_mobile/modules/tizen/WidgetDB/config.cmake create mode 100644 src_mobile/modules/tizen/WidgetInterface/CMakeLists.txt create mode 100644 src_mobile/modules/tizen/WidgetInterface/WidgetInterface.cpp create mode 100644 src_mobile/modules/tizen/WidgetInterface/WidgetInterface.h create mode 100644 src_mobile/modules/tizen/WidgetInterface/config.cmake create mode 100644 src_mobile/modules/tizen/config.cmake create mode 100644 src_mobile/plugin-loading/CMakeLists.txt create mode 100644 src_mobile/plugin-loading/explorer.cpp create mode 100644 src_mobile/plugin-loading/explorer.h create mode 100644 src_mobile/plugin-loading/javascript_interface.cpp create mode 100644 src_mobile/plugin-loading/javascript_interface.h create mode 100644 src_mobile/plugin-loading/js_page_session.cpp create mode 100644 src_mobile/plugin-loading/js_page_session.h create mode 100644 src_mobile/plugin-loading/js_types.h create mode 100644 src_mobile/plugin-loading/plugin.cpp create mode 100644 src_mobile/plugin-loading/plugin.h create mode 100644 src_mobile/plugin-loading/plugin_container_support.cpp create mode 100644 src_mobile/plugin-loading/plugin_container_support.h create mode 100644 src_mobile/plugin-loading/plugin_iframe_support.cpp create mode 100644 src_mobile/plugin-loading/plugin_iframe_support.h create mode 100644 src_mobile/plugin-loading/plugin_logic.cpp create mode 100644 src_mobile/plugin-loading/plugin_logic.h create mode 100644 src_mobile/plugin-loading/plugin_model.cpp create mode 100644 src_mobile/plugin-loading/plugin_model.h create mode 100644 src_mobile/plugin-loading/plugin_property_support.cpp create mode 100644 src_mobile/plugin-loading/plugin_property_support.h create mode 100644 src_mobile/plugins-api-support/CMakeLists.txt create mode 100644 src_mobile/plugins-api-support/CallbackSupport.h create mode 100644 src_mobile/plugins-api-support/ExportedApi.h create mode 100644 src_mobile/plugins-api-support/IObject.h create mode 100644 src_mobile/plugins-api-support/IObject_cast.h create mode 100644 src_mobile/plugins-api-support/Object.cpp create mode 100644 src_mobile/plugins-api-support/Object.h create mode 100644 src_mobile/plugins-api-support/ObjectFactory.cpp create mode 100644 src_mobile/plugins-api-support/ObjectFactory.h create mode 100644 src_mobile/plugins-api-support/Plugin.cpp create mode 100644 src_mobile/plugins-api-support/Plugin.h create mode 100644 src_mobile/plugins-api-support/PluginRegistration.cpp create mode 100644 src_mobile/plugins-api-support/PluginRegistration.h create mode 100644 src_mobile/plugins-api-support/PluginRegistrationImpl.h create mode 100644 src_mobile/plugins-api-support/PluginRegistry.cpp create mode 100644 src_mobile/plugins-api-support/PluginRegistry.h create mode 100644 src_mobile/plugins-api-support/PluginSignals.h create mode 100644 src_mobile/plugins-api-support/SignalSignature.h create mode 100644 src_mobile/plugins-api-support/SignalsSupport.h create mode 100644 src_mobile/plugins-api-support/SoFeatures.h create mode 100644 src_mobile/plugins-api-support/detail/traits.h create mode 100644 src_mobile/plugins-api-support/js_types.h create mode 100644 src_mobile/plugins-api-support/traits.h create mode 100644 src_mobile/plugins-api-support/tuple.h create mode 100644 src_mobile/plugins-installer/CMakeLists.txt create mode 100644 src_mobile/plugins-installer/DESCRIPTION create mode 100644 src_mobile/plugins-installer/plugin_installer.cpp create mode 100644 src_mobile/plugins-installer/plugin_installer.h create mode 100644 src_mobile/plugins-installer/plugin_installer_errors.h create mode 100644 src_mobile/plugins-installer/plugin_installer_types.h create mode 100644 src_mobile/plugins-installer/plugin_metafile_reader.cpp create mode 100644 src_mobile/plugins-installer/plugin_metafile_reader.h create mode 100644 src_mobile/plugins-installer/plugin_objects.cpp create mode 100644 src_mobile/plugins-installer/plugin_objects.h create mode 100644 src_mobile/plugins-installer/plugin_utils.cpp create mode 100644 src_mobile/plugins-installer/plugin_utils.h create mode 100644 src_mobile/plugins-installer/wrt_plugins_installer.cpp create mode 100644 src_mobile/plugins-ipc-message/CMakeLists.txt create mode 100644 src_mobile/plugins-ipc-message/ipc_message_support.cpp create mode 100644 src_mobile/plugins-ipc-message/ipc_message_support.h create mode 100644 src_mobile/standards/CMakeLists.txt create mode 100644 src_mobile/standards/W3C/CMakeLists.txt create mode 100644 src_mobile/standards/W3C/DESCRIPTION create mode 100644 src_mobile/standards/W3C/Widget/CMakeLists.txt create mode 100644 src_mobile/standards/W3C/Widget/JSPreferences.cpp create mode 100644 src_mobile/standards/W3C/Widget/JSPreferences.h create mode 100644 src_mobile/standards/W3C/Widget/JSWidget.cpp create mode 100644 src_mobile/standards/W3C/Widget/JSWidget.h create mode 100644 src_mobile/standards/W3C/Widget/plugin_config.cpp create mode 100644 src_mobile/standards/W3C/Widget/plugin_config.h create mode 100644 src_mobile/standards/W3C/Widget/plugin_initializer.cpp create mode 100755 src_mobile/wrt-popup/CMakeLists.txt create mode 100755 src_mobile/wrt-popup/ace/CMakeLists.txt create mode 100644 src_mobile/wrt-popup/ace/popup-bin/CMakeLists.txt create mode 100644 src_mobile/wrt-popup/ace/popup-bin/Popup.cpp create mode 100644 src_mobile/wrt-popup/ace/popup-bin/Popup.h create mode 100644 src_mobile/wrt-popup/ace/popup-runner/CMakeLists.txt create mode 100644 src_mobile/wrt-popup/ace/popup-runner/popup-runner.cpp create mode 100644 src_mobile/wrt-popup/ace/popup-runner/popup-runner.h create mode 100755 src_mobile/wrt-popup/wrt/CMakeLists.txt create mode 100644 src_mobile/wrt-popup/wrt/PopupEnum.h create mode 100644 src_mobile/wrt-popup/wrt/PopupSerializer.cpp create mode 100644 src_mobile/wrt-popup/wrt/PopupSerializer.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/CMakeLists.txt create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_object.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.h create mode 100644 src_mobile/wrt-popup/wrt/popup-runner/CMakeLists.txt create mode 100644 src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.cpp create mode 100644 src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.h create mode 100644 src_wearable/CMakeLists.txt create mode 100644 src_wearable/Commons/Base64.cpp create mode 100644 src_wearable/Commons/Base64.h create mode 100644 src_wearable/Commons/CMakeLists.txt create mode 100644 src_wearable/Commons/DESCRIPTION create mode 100644 src_wearable/Commons/Deprecated.h create mode 100644 src_wearable/Commons/Dimension.h create mode 100644 src_wearable/Commons/Emitters.h create mode 100644 src_wearable/Commons/EventListener.h create mode 100644 src_wearable/Commons/EventReceiver.h create mode 100644 src_wearable/Commons/Exception.h create mode 100644 src_wearable/Commons/FunctionDeclaration.h create mode 100644 src_wearable/Commons/FunctionDefinition.cpp create mode 100644 src_wearable/Commons/FunctionDefinition.h create mode 100644 src_wearable/Commons/IEvent.h create mode 100644 src_wearable/Commons/IExternEventCanceler.h create mode 100644 src_wearable/Commons/JSObject.cpp create mode 100644 src_wearable/Commons/JSObject.h create mode 100755 src_wearable/Commons/JSObjectDeclaration.cpp create mode 100644 src_wearable/Commons/JSObjectDeclaration.h create mode 100644 src_wearable/Commons/ListenerEvent.h create mode 100644 src_wearable/Commons/ListenerEventEmitter.h create mode 100644 src_wearable/Commons/Range.h create mode 100644 src_wearable/Commons/Regex.cpp create mode 100644 src_wearable/Commons/Regex.h create mode 100644 src_wearable/Commons/RegexPatterns.h create mode 100644 src_wearable/Commons/RegexUtils.cpp create mode 100644 src_wearable/Commons/RegexUtils.h create mode 100644 src_wearable/Commons/StaticAssert.h create mode 100644 src_wearable/Commons/StringBuilder.cpp create mode 100644 src_wearable/Commons/StringBuilder.h create mode 100644 src_wearable/Commons/StringUtils.cpp create mode 100644 src_wearable/Commons/StringUtils.h create mode 100644 src_wearable/Commons/ThreadPool.cpp create mode 100644 src_wearable/Commons/ThreadPool.h create mode 100644 src_wearable/Commons/TimeUtils.cpp create mode 100644 src_wearable/Commons/TimeUtils.h create mode 100644 src_wearable/Commons/TypeTraits.h create mode 100644 src_wearable/Commons/TypesDeclaration.h create mode 100644 src_wearable/Commons/WrtAccess/WrtAccess.cpp create mode 100644 src_wearable/Commons/WrtAccess/WrtAccess.h create mode 100644 src_wearable/Commons/WrtAccess/config.cmake create mode 100644 src_wearable/Commons/plugin_initializer_def.h create mode 100755 src_wearable/CommonsJavaScript/CMakeLists.txt create mode 100644 src_wearable/CommonsJavaScript/Converter.cpp create mode 100644 src_wearable/CommonsJavaScript/Converter.h create mode 100644 src_wearable/CommonsJavaScript/DESCRIPTION create mode 100644 src_wearable/CommonsJavaScript/DOMExceptionData.cpp create mode 100644 src_wearable/CommonsJavaScript/DOMExceptionData.h create mode 100644 src_wearable/CommonsJavaScript/JSCallbackManager.cpp create mode 100644 src_wearable/CommonsJavaScript/JSCallbackManager.h create mode 100644 src_wearable/CommonsJavaScript/JSDOMException.cpp create mode 100644 src_wearable/CommonsJavaScript/JSDOMException.h create mode 100644 src_wearable/CommonsJavaScript/JSDOMExceptionFactory.cpp create mode 100644 src_wearable/CommonsJavaScript/JSDOMExceptionFactory.h create mode 100644 src_wearable/CommonsJavaScript/JSPendingOperation.cpp create mode 100644 src_wearable/CommonsJavaScript/JSPendingOperation.h create mode 100644 src_wearable/CommonsJavaScript/JSPendingOperationPrivateObject.h create mode 100644 src_wearable/CommonsJavaScript/JSUtils.cpp create mode 100644 src_wearable/CommonsJavaScript/JSUtils.h create mode 100644 src_wearable/CommonsJavaScript/PrivateObject.h create mode 100644 src_wearable/CommonsJavaScript/ScopedJSStringRef.cpp create mode 100644 src_wearable/CommonsJavaScript/ScopedJSStringRef.h create mode 100644 src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp create mode 100644 src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.h create mode 100644 src_wearable/CommonsJavaScript/Security/StaticDeclaration.h create mode 100644 src_wearable/CommonsJavaScript/SecurityExceptions.h create mode 100644 src_wearable/CommonsJavaScript/SupportPendingOperation.h create mode 100644 src_wearable/CommonsJavaScript/Utils.h create mode 100644 src_wearable/CommonsJavaScript/Validator.cpp create mode 100644 src_wearable/CommonsJavaScript/Validator.h create mode 100644 src_wearable/DESCRIPTION create mode 100644 src_wearable/dispatch-event/CMakeLists.txt create mode 100644 src_wearable/dispatch-event/dispatch_event_support.cpp create mode 100644 src_wearable/dispatch-event/dispatch_event_support.h create mode 100644 src_wearable/js-overlay/CMakeLists.txt create mode 100644 src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp create mode 100644 src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h create mode 100644 src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.cpp create mode 100644 src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.h create mode 100644 src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp create mode 100644 src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h create mode 100755 src_wearable/js-overlay/deprecated/js_iframe_support.cpp create mode 100755 src_wearable/js-overlay/deprecated/js_iframe_support.h create mode 100755 src_wearable/js-overlay/deprecated/js_overlay_addEventListener.cpp create mode 100755 src_wearable/js-overlay/deprecated/js_overlay_addEventListener.h create mode 100644 src_wearable/js-overlay/deprecated/js_overlay_support.cpp create mode 100644 src_wearable/js-overlay/deprecated/js_overlay_support.h create mode 100644 src_wearable/js-overlay/js_function_manager.cpp create mode 100644 src_wearable/js-overlay/js_function_manager.h create mode 100644 src_wearable/js-overlay/js_overlay_functions.cpp create mode 100644 src_wearable/js-overlay/js_overlay_functions.h create mode 100644 src_wearable/js-overlay/js_overlay_types.h create mode 100644 src_wearable/modules/API/CMakeLists.txt create mode 100644 src_wearable/modules/API/DESCRIPTION create mode 100644 src_wearable/modules/API/Filesystem/Enums.h create mode 100644 src_wearable/modules/API/Filesystem/EventCopy.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventCopy.h create mode 100644 src_wearable/modules/API/Filesystem/EventFind.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventFind.h create mode 100644 src_wearable/modules/API/Filesystem/EventListNodes.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventListNodes.h create mode 100644 src_wearable/modules/API/Filesystem/EventMove.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventMove.h create mode 100644 src_wearable/modules/API/Filesystem/EventOpen.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventOpen.h create mode 100644 src_wearable/modules/API/Filesystem/EventReadText.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventReadText.h create mode 100644 src_wearable/modules/API/Filesystem/EventRemove.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventRemove.h create mode 100644 src_wearable/modules/API/Filesystem/EventResolve.cpp create mode 100644 src_wearable/modules/API/Filesystem/EventResolve.h create mode 100644 src_wearable/modules/API/Filesystem/IManager.cpp create mode 100644 src_wearable/modules/API/Filesystem/IManager.h create mode 100644 src_wearable/modules/API/Filesystem/INode.cpp create mode 100644 src_wearable/modules/API/Filesystem/INode.h create mode 100644 src_wearable/modules/API/Filesystem/INodeTypes.h create mode 100644 src_wearable/modules/API/Filesystem/IPath.cpp create mode 100644 src_wearable/modules/API/Filesystem/IPath.h create mode 100644 src_wearable/modules/API/Filesystem/IStream.cpp create mode 100644 src_wearable/modules/API/Filesystem/IStream.h create mode 100644 src_wearable/modules/API/Filesystem/NodeFilter.cpp create mode 100644 src_wearable/modules/API/Filesystem/NodeFilter.h create mode 100644 src_wearable/modules/API/Filesystem/PathUtils.cpp create mode 100644 src_wearable/modules/API/Filesystem/PathUtils.h create mode 100644 src_wearable/modules/API/Filesystem/config.cmake create mode 100644 src_wearable/modules/API/LocalStorage/ILocalStorage.h create mode 100644 src_wearable/modules/API/LocalStorage/LocalStorageMgr.cpp create mode 100644 src_wearable/modules/API/LocalStorage/LocalStorageMgr.h create mode 100644 src_wearable/modules/API/LocalStorage/config.cmake create mode 100644 src_wearable/modules/API/PluginManager/IPluginManager.h create mode 100644 src_wearable/modules/API/PluginManager/PluginManagerFactory.cpp create mode 100644 src_wearable/modules/API/PluginManager/PluginManagerFactory.h create mode 100644 src_wearable/modules/API/PluginManager/config.cmake create mode 100644 src_wearable/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h create mode 100644 src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp create mode 100644 src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h create mode 100644 src_wearable/modules/API/SoftKeyboardChangeEvent/config.cmake create mode 100644 src_wearable/modules/API/StorageEvent/IStorageEvent.h create mode 100644 src_wearable/modules/API/StorageEvent/StorageEvent.cpp create mode 100644 src_wearable/modules/API/StorageEvent/StorageEvent.h create mode 100644 src_wearable/modules/API/StorageEvent/StorageEventMgr.cpp create mode 100644 src_wearable/modules/API/StorageEvent/StorageEventMgr.h create mode 100644 src_wearable/modules/API/StorageEvent/config.cmake create mode 100644 src_wearable/modules/API/TizenServiceEvent/ITizenServiceEvent.h create mode 100644 src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.cpp create mode 100644 src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.h create mode 100644 src_wearable/modules/API/TizenServiceEvent/config.cmake create mode 100644 src_wearable/modules/API/Widget/IWidget.h create mode 100644 src_wearable/modules/API/Widget/WidgetFactory.cpp create mode 100644 src_wearable/modules/API/Widget/WidgetFactory.h create mode 100644 src_wearable/modules/API/Widget/config.cmake create mode 100644 src_wearable/modules/API/WidgetDB/IWidgetDB.h create mode 100644 src_wearable/modules/API/WidgetDB/IWidgetFeature.h create mode 100644 src_wearable/modules/API/WidgetDB/WidgetDBMgr.cpp create mode 100644 src_wearable/modules/API/WidgetDB/WidgetDBMgr.h create mode 100644 src_wearable/modules/API/WidgetDB/config.cmake create mode 100644 src_wearable/modules/API/config.cmake create mode 100644 src_wearable/modules/CMakeLists.txt create mode 100644 src_wearable/modules/DESCRIPTION create mode 100644 src_wearable/modules/packages/CMakeLists.txt create mode 100644 src_wearable/modules/packages/Filesystem/CMakeLists.txt create mode 100644 src_wearable/modules/packages/LocalStorage/CMakeLists.txt create mode 100644 src_wearable/modules/packages/PluginManager/CMakeLists.txt create mode 100644 src_wearable/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt create mode 100644 src_wearable/modules/packages/StorageEvent/CMakeLists.txt create mode 100644 src_wearable/modules/packages/TizenServiceEvent/CMakeLists.txt create mode 100644 src_wearable/modules/packages/Widget/CMakeLists.txt create mode 100644 src_wearable/modules/packages/WidgetDB/CMakeLists.txt create mode 100644 src_wearable/modules/packages/WidgetInterface/CMakeLists.txt create mode 100644 src_wearable/modules/tizen/CMakeLists.txt create mode 100644 src_wearable/modules/tizen/DESCRIPTION create mode 100644 src_wearable/modules/tizen/Filesystem/Manager.cpp create mode 100644 src_wearable/modules/tizen/Filesystem/Manager.h create mode 100644 src_wearable/modules/tizen/Filesystem/Node.cpp create mode 100644 src_wearable/modules/tizen/Filesystem/Node.h create mode 100644 src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.cpp create mode 100644 src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.h create mode 100644 src_wearable/modules/tizen/Filesystem/Path.cpp create mode 100644 src_wearable/modules/tizen/Filesystem/Path.h create mode 100644 src_wearable/modules/tizen/Filesystem/Stream.cpp create mode 100644 src_wearable/modules/tizen/Filesystem/Stream.h create mode 100644 src_wearable/modules/tizen/Filesystem/Utils.cpp create mode 100644 src_wearable/modules/tizen/Filesystem/Utils.h create mode 100644 src_wearable/modules/tizen/Filesystem/config.cmake create mode 100644 src_wearable/modules/tizen/PluginManager/PluginManager.cpp create mode 100644 src_wearable/modules/tizen/PluginManager/PluginManager.h create mode 100644 src_wearable/modules/tizen/PluginManager/config.cmake create mode 100644 src_wearable/modules/tizen/Widget/Property.h create mode 100644 src_wearable/modules/tizen/Widget/Widget.cpp create mode 100644 src_wearable/modules/tizen/Widget/Widget.h create mode 100644 src_wearable/modules/tizen/Widget/config.cmake create mode 100644 src_wearable/modules/tizen/WidgetDB/WidgetDB.cpp create mode 100644 src_wearable/modules/tizen/WidgetDB/WidgetDB.h create mode 100644 src_wearable/modules/tizen/WidgetDB/WidgetFeature.cpp create mode 100644 src_wearable/modules/tizen/WidgetDB/WidgetFeature.h create mode 100644 src_wearable/modules/tizen/WidgetDB/config.cmake create mode 100644 src_wearable/modules/tizen/WidgetInterface/CMakeLists.txt create mode 100644 src_wearable/modules/tizen/WidgetInterface/WidgetInterface.cpp create mode 100644 src_wearable/modules/tizen/WidgetInterface/WidgetInterface.h create mode 100644 src_wearable/modules/tizen/WidgetInterface/config.cmake create mode 100644 src_wearable/modules/tizen/config.cmake create mode 100644 src_wearable/plugin-loading/CMakeLists.txt create mode 100644 src_wearable/plugin-loading/explorer.cpp create mode 100644 src_wearable/plugin-loading/explorer.h create mode 100644 src_wearable/plugin-loading/javascript_interface.cpp create mode 100644 src_wearable/plugin-loading/javascript_interface.h create mode 100644 src_wearable/plugin-loading/js_page_session.cpp create mode 100644 src_wearable/plugin-loading/js_page_session.h create mode 100644 src_wearable/plugin-loading/js_types.h create mode 100644 src_wearable/plugin-loading/plugin.cpp create mode 100644 src_wearable/plugin-loading/plugin.h create mode 100644 src_wearable/plugin-loading/plugin_container_support.cpp create mode 100644 src_wearable/plugin-loading/plugin_container_support.h create mode 100644 src_wearable/plugin-loading/plugin_iframe_support.cpp create mode 100644 src_wearable/plugin-loading/plugin_iframe_support.h create mode 100644 src_wearable/plugin-loading/plugin_logic.cpp create mode 100644 src_wearable/plugin-loading/plugin_logic.h create mode 100644 src_wearable/plugin-loading/plugin_model.cpp create mode 100644 src_wearable/plugin-loading/plugin_model.h create mode 100644 src_wearable/plugin-loading/plugin_property_support.cpp create mode 100644 src_wearable/plugin-loading/plugin_property_support.h create mode 100644 src_wearable/plugins-api-support/CMakeLists.txt create mode 100644 src_wearable/plugins-api-support/CallbackSupport.h create mode 100644 src_wearable/plugins-api-support/ExportedApi.h create mode 100644 src_wearable/plugins-api-support/IObject.h create mode 100644 src_wearable/plugins-api-support/IObject_cast.h create mode 100644 src_wearable/plugins-api-support/Object.cpp create mode 100644 src_wearable/plugins-api-support/Object.h create mode 100644 src_wearable/plugins-api-support/ObjectFactory.cpp create mode 100644 src_wearable/plugins-api-support/ObjectFactory.h create mode 100644 src_wearable/plugins-api-support/Plugin.cpp create mode 100644 src_wearable/plugins-api-support/Plugin.h create mode 100644 src_wearable/plugins-api-support/PluginRegistration.cpp create mode 100644 src_wearable/plugins-api-support/PluginRegistration.h create mode 100644 src_wearable/plugins-api-support/PluginRegistrationImpl.h create mode 100644 src_wearable/plugins-api-support/PluginRegistry.cpp create mode 100644 src_wearable/plugins-api-support/PluginRegistry.h create mode 100644 src_wearable/plugins-api-support/PluginSignals.h create mode 100644 src_wearable/plugins-api-support/SignalSignature.h create mode 100644 src_wearable/plugins-api-support/SignalsSupport.h create mode 100644 src_wearable/plugins-api-support/detail/traits.h create mode 100644 src_wearable/plugins-api-support/js_types.h create mode 100644 src_wearable/plugins-api-support/traits.h create mode 100644 src_wearable/plugins-api-support/tuple.h create mode 100644 src_wearable/plugins-installer/CMakeLists.txt create mode 100644 src_wearable/plugins-installer/DESCRIPTION create mode 100644 src_wearable/plugins-installer/plugin_installer.cpp create mode 100644 src_wearable/plugins-installer/plugin_installer.h create mode 100644 src_wearable/plugins-installer/plugin_installer_errors.h create mode 100644 src_wearable/plugins-installer/plugin_installer_types.h create mode 100644 src_wearable/plugins-installer/plugin_metafile_reader.cpp create mode 100644 src_wearable/plugins-installer/plugin_metafile_reader.h create mode 100644 src_wearable/plugins-installer/plugin_objects.cpp create mode 100644 src_wearable/plugins-installer/plugin_objects.h create mode 100644 src_wearable/plugins-installer/plugin_utils.cpp create mode 100644 src_wearable/plugins-installer/plugin_utils.h create mode 100644 src_wearable/plugins-installer/wrt_plugins_installer.cpp create mode 100644 src_wearable/plugins-ipc-message/CMakeLists.txt create mode 100644 src_wearable/plugins-ipc-message/ipc_message_support.cpp create mode 100644 src_wearable/plugins-ipc-message/ipc_message_support.h create mode 100644 src_wearable/standards/CMakeLists.txt create mode 100644 src_wearable/standards/W3C/CMakeLists.txt create mode 100644 src_wearable/standards/W3C/DESCRIPTION create mode 100644 src_wearable/standards/W3C/Widget/CMakeLists.txt create mode 100644 src_wearable/standards/W3C/Widget/JSPreferences.cpp create mode 100644 src_wearable/standards/W3C/Widget/JSPreferences.h create mode 100644 src_wearable/standards/W3C/Widget/JSWidget.cpp create mode 100644 src_wearable/standards/W3C/Widget/JSWidget.h create mode 100644 src_wearable/standards/W3C/Widget/plugin_config.cpp create mode 100644 src_wearable/standards/W3C/Widget/plugin_config.h create mode 100644 src_wearable/standards/W3C/Widget/plugin_initializer.cpp create mode 100755 src_wearable/wrt-popup/CMakeLists.txt create mode 100755 src_wearable/wrt-popup/ace/CMakeLists.txt create mode 100644 src_wearable/wrt-popup/ace/popup-bin/CMakeLists.txt create mode 100644 src_wearable/wrt-popup/ace/popup-bin/Popup.cpp create mode 100644 src_wearable/wrt-popup/ace/popup-bin/Popup.h create mode 100644 src_wearable/wrt-popup/ace/popup-runner/CMakeLists.txt create mode 100644 src_wearable/wrt-popup/ace/popup-runner/popup-runner.cpp create mode 100644 src_wearable/wrt-popup/ace/popup-runner/popup-runner.h create mode 100755 src_wearable/wrt-popup/wrt/CMakeLists.txt create mode 100644 src_wearable/wrt-popup/wrt/PopupEnum.h create mode 100644 src_wearable/wrt-popup/wrt/PopupSerializer.cpp create mode 100644 src_wearable/wrt-popup/wrt/PopupSerializer.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/CMakeLists.txt create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_object.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.h create mode 100644 src_wearable/wrt-popup/wrt/popup-runner/CMakeLists.txt create mode 100644 src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.cpp create mode 100644 src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.h create mode 100644 tests/CMakeLists.txt create mode 100644 tests/CMakeUtils.txt create mode 100644 tests/dao/CMakeLists.txt create mode 100644 tests/dao/README create mode 100644 tests/dao/TestInit.cpp create mode 100644 tests/dao/WidgetDBTest.cpp create mode 100755 tests/dao/widgetdb_tests_prepare_db.sh create mode 100644 uncrustify.cfg create mode 100755 uncrustify.sh create mode 100644 wrt-plugins-common.manifest create mode 100644 wrt-plugins-common.map create mode 100644 wrt-popup-ace-runtime.mobile.rule create mode 100644 wrt-popup-ace-runtime.mobile2.rule create mode 100644 wrt-popup-ace-runtime.rule create mode 100644 wrt-popup-wrt-runtime.mobile.rule create mode 100644 wrt-popup-wrt-runtime.mobile2.rule create mode 100644 wrt-popup-wrt-runtime.rule diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f32cf97 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +CMakeCache.txt +CMakeFiles/ +build-stamp +cmake_install.cmake +config.guess +config.sub +configure-stamp +debian/files +debian/tmp/ +install_manifest.txt +Makefile +debian/wrt-plugins-dev.install +debian/wrt-plugins.install +debian/wrt-plugins.postinst +debian/wrt-plugins-common-dbg.debhelper.log +debian/wrt-plugins-common-dbg.substvars +debian/wrt-plugins-common-dbg/ +debian/wrt-plugins-common.debhelper.log +debian/wrt-plugins-common.substvars +debian/wrt-plugins-common/ +src/Makefile + +debian/wrt-plugins-common-dev.debhelper.log +debian/wrt-plugins-common-dev.install +debian/wrt-plugins-common-dev.substvars +debian/wrt-plugins-common-dev/ +debian/wrt-plugins-common.install +debian/wrt-plugins-common.postinst +debian/wrt-plugins-common.postinst.debhelper +debian/wrt-plugins-common.postrm.debhelper + +pkgconfigs/*.pc + +*~ +*.swp +cmake_build/* + +/bin diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..8978700 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,189 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +cmake_minimum_required(VERSION 2.6) + +SET(CMAKE_PROJECT_NAME wrt-plugins-common) +set(PACKAGE_NAME ${CMAKE_PROJECT_NAME}) +project(${CMAKE_PROJECT_NAME}) +STRING(REGEX MATCH "([^.]*)" CMAKE_PROJECT_API_VERSION "${CMAKE_PROJECT_VERSION}") + +################################################################################ +# Required platform modules + +include(FindPkgConfig) + +pkg_search_module(dpl REQUIRED dpl-efl>=0.2.21) + +include_directories( + ${dpl_INCLUDE_DIRS} + ${CMAKE_CURRENT_SOURCE_DIR}/src/ + ${CMAKE_CURRENT_SOURCE_DIR}/src/modules/API + ${CMAKE_CURRENT_SOURCE_DIR}/src/Commons + ${CMAKE_CURRENT_SOURCE_DIR}/src/CommonsJavaScript + ${CMAKE_CURRENT_SOURCE_DIR}/src/plugin-loading + ${CMAKE_CURRENT_SOURCE_DIR}/src/js-overlay + ${CMAKE_CURRENT_SOURCE_DIR}/src/wrt-popup/ace/popup-runner + ${CMAKE_CURRENT_SOURCE_DIR}/src/plugins_ipc_message + ${CMAKE_CURRENT_SOURCE_DIR}/src/dispatch-event) + +############################################################################## +# Build type +IF(NOT CMAKE_BUILD_TYPE) + SET(CMAKE_BUILD_TYPE "Release") +ENDIF(NOT CMAKE_BUILD_TYPE) + +# Compiler flags +SET(CMAKE_C_FLAGS_PROFILING "-O2") +SET(CMAKE_CXX_FLAGS_PROFILING "-O2 -std=c++0x") +SET(CMAKE_C_FLAGS_DEBUG "-O0 -g") +SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE "-Os") +SET(CMAKE_CXX_FLAGS_RELEASE "-Os -std=c++0x -fvisibility-inlines-hidden") +SET(CMAKE_CXX_FLAGS_CCOV "-O0 -std=c++0x -g --coverage") +#### + +OPTION(DPL_LOG "DPL logs status" ON) +OPTION(WITH_TESTS "Build tests" OFF) + +IF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") + MESSAGE(STATUS "Logging enabled for DPL") + ADD_DEFINITIONS("-DDPL_LOGS_ENABLED") +ELSE(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") + MESSAGE(STATUS "Logging disabled for DPL") +ENDIF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") + +MESSAGE(STATUS "WITH_TESTS: " ${WITH_TESTS}) + +ADD_DEFINITIONS("-fPIC") +ADD_DEFINITIONS("-fvisibility=default") # mark all exported symbols as visible +ADD_DEFINITIONS("-fPIC") # If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding +ADD_DEFINITIONS("-DEXPORT_API=") +ADD_DEFINITIONS("-Wall") +#ADD_DEFINITIONS("-Werror") +ADD_DEFINITIONS("-Wextra") +ADD_DEFINITIONS("-Wno-deprecated") +#ADD_DEFINITIONS("-DDEVPKG") +# GCC 4.7 changes the scheme of name lookup. Guide: http://gcc.gnu.org/gcc-4.7/porting_to.html +ADD_DEFINITIONS("-fpermissive") + +############################################################################## +# CMake flags +IF (DEVPKG) + SET(DEVPKG "ON") +ENDIF(DEVPKG) + +################################################################################ +# Miscellaneous variables + +set(CONFIG_FILE_NAME "config.cmake") +set(LIBS_COMMONS ${dpl_LDFLAGS} ) + +set(DESTINATION_LIB_PREFIX lib) +set(DESTINATION_HEADER_PREFIX include/${PROJECT_NAME}) + +set(DESTINATION_HEADERS_NON_JS ${DESTINATION_HEADER_PREFIX}/Commons) +set(DESTINATION_HEADERS_JS ${DESTINATION_HEADER_PREFIX}/CommonsJavaScript) +set(DESTINATION_HEADERS_JS_OVERLAY ${DESTINATION_HEADER_PREFIX}/js-overlay) +set(DESTINATION_HEADERS_WRT_POPUP_RUNNER ${DESTINATION_HEADER_PREFIX}/popup-runner) + +################################################################################ +# Target platform + +if (NOT DEFINED PLATFORM) + set(PLATFORM "tizen") +endif () + +################################################################################ +# Schema of plugin's configuration file + +set(COMMON_CONFIG_DTD ${CMAKE_CURRENT_SOURCE_DIR}/config.dtd) +set(COMMON_CONFIG_DTD_DST /usr/etc/wrt-plugins) +INSTALL(FILES ${COMMON_CONFIG_DTD} DESTINATION ${COMMON_CONFIG_DTD_DST}) + +################################################################################ +# Macros used for including plugins from AL. + + +function(add_subdir NAME) + message(STATUS "Building: ${CMAKE_CURRENT_SOURCE_DIR}/${NAME}") + add_subdirectory(${NAME}) +endfunction() + +################################################################################ +# Subdirectories + +add_subdirectory(src) + +IF(WITH_TESTS) + add_subdirectory(tests) +ENDIF(WITH_TESTS) + +################################################################################ +# PKGCONFIG + +set(PKGCONFIG_DIR ${PROJECT_SOURCE_DIR}/pkgconfigs) + +macro(configure_and_install_pkg PKG_FILE) + CONFIGURE_FILE(${PKGCONFIG_DIR}/${PKG_FILE}.in + ${PKGCONFIG_DIR}/${PKG_FILE} @ONLY) + INSTALL(FILES ${PKGCONFIG_DIR}/${PKG_FILE} DESTINATION lib/pkgconfig) +endmacro(configure_and_install_pkg) + +configure_and_install_pkg(wrt-plugins-commons-javascript.pc) +configure_and_install_pkg(wrt-plugins-commons.pc) +configure_and_install_pkg(wrt-plugins-filesystem.pc) +configure_and_install_pkg(wrt-plugins-widget-interface.pc) +configure_and_install_pkg(wrt-plugins-widgetdb.pc) +configure_and_install_pkg(wrt-plugins-plugin-manager.pc) +configure_and_install_pkg(wrt-plugin-loading.pc) +configure_and_install_pkg(wrt-plugin-js-overlay.pc) +configure_and_install_pkg(wrt-popup-runner.pc) +configure_and_install_pkg(wrt-popup-ace-runner.pc) +configure_and_install_pkg(wrt-popup-wrt-runner.pc) +configure_and_install_pkg(wrt-plugins-api-support.pc) +configure_and_install_pkg(wrt-plugins-ipc-message.pc) +configure_and_install_pkg(wrt-dispatch-event.pc) + +################################################################################ +# Cache + +set(PLATFORM "${PLATFORM}" CACHE STRING "Target platform" FORCE) +set(CMAKE_CONFIG_FILE_NAME "${CMAKE_CONFIG_FILE_NAME}" CACHE + STRING "CMake configuration file name." FORCE) + +################################################################################ +# SMACK rule + +IF(DEVICE_PROFILE STREQUAL "wearable") +# werable +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-ace-runtime.rule DESTINATION /etc/smack/accesses2.d) +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-wrt-runtime.rule DESTINATION /etc/smack/accesses2.d) +# +ELSE(DEVICE_PROFILE STREQUAL "wearable") +# mobile +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-ace-runtime.mobile.rule DESTINATION /etc/smack/accesses2.d) +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-wrt-runtime.mobile.rule DESTINATION /etc/smack/accesses2.d) +# temp for smack branch +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-ace-runtime.mobile2.rule DESTINATION /opt/etc/smack/accesses.d) +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-wrt-runtime.mobile2.rule DESTINATION /opt/etc/smack/accesses.d) +# +ENDIF(DEVICE_PROFILE STREQUAL "wearable") + + + +################################################################################ +# Summary + +message(STATUS "PLATFORM = ${PLATFORM}") diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..247c97d --- /dev/null +++ b/LICENSE @@ -0,0 +1,203 @@ +Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..ded3804 --- /dev/null +++ b/NOTICE @@ -0,0 +1 @@ +Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. \ No newline at end of file diff --git a/clean.sh b/clean.sh new file mode 100755 index 0000000..d5d143a --- /dev/null +++ b/clean.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +echo Performing clean + +function clean { + rm -rf CMakeCache.txt + rm -rf CMakeFiles + rm -rf cmake_install.cmake + rm -rf Makefile + rm -rf install_manifest.txt + + for i in `ls`; do + if [ -d $i ]; then + cd $i; + clean; + cd .. + fi + done + } + + clean + + + diff --git a/config.dtd b/config.dtd new file mode 100644 index 0000000..d335eff --- /dev/null +++ b/config.dtd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dir-struct.py b/dir-struct.py new file mode 100755 index 0000000..1d5edab --- /dev/null +++ b/dir-struct.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import re + + +def countLines(path): + with open(path) as f: + return len(f.readlines()) + +# RETURNS: ( +# short description (string or None) +# long decsription (array of strings or None) +# options: stop +def parseDescr(lines): + if len(lines) == 0: + return (None, None, False) + linesRest = None + if re.match( r"!!!options!!!", lines[0] ): + optStop = True + linesRest = lines[1:] + else: + optStop = False + linesRest = lines + if len(linesRest) == 0: + return(None,None,optStop) + short = linesRest[0].rstrip() + long = [] + for l in linesRest[1:]: + ll = l.rstrip() + if re.search( r"\S", ll ): + long.append( ll ) + if len(long) == 0: + long = None + + return (short, long, optStop) + +# RETURNS a tree with nodes like: ( +# path (string) +# short description (string or None) +# long decsription (array of strings or None) +# LOC (integer) +# list of subdirs (child nodes like this one) +def parseDir(path): + short = None + long = None + optStop = False + try: + with open( path+'/DESCRIPTION' ) as f: + short, long, optStop = parseDescr( f.readlines() ) + except IOError: + pass + dirs = [] + cntLines = 0 + for fname in os.listdir(path): + if fname != '.git' and os.path.isdir(path+'/'+fname): + subdir = parseDir(path+'/'+fname) + if optStop == False: + dirs.append(subdir) + (dummy0, dummy1, dummy2, subLines, dummy4) = subdir + cntLines += subLines + + if os.path.isfile(path+'/'+fname) \ + and not os.path.islink(path+'/'+fname): + cntLines += countLines(path+'/'+fname) + + return path, short, long, cntLines, dirs + +##### PRINT AS a sort of CSV delimited by '|' + +# indent is a number (0..) +def printTabSub(tree,indent): + path, short, long, loc, subdirs = tree + p = re.sub(r"^\./", '', path) + m = re.search(r"/([^/]*$)", p) + if m != None: p = m.groups()[0] + if short == None: + print '%s%s|%d|' % (" "*indent, p, loc) + else: + print '%s%s|%d|%s' % (" "*indent, p, loc, short) + for dir in subdirs: + printTabSub(dir, indent+1) + +def printTab(tree): + printTabSub(tree,0) + +def printTabWoMain(tree): + path, short, long, loc, dirs = tree + for dir in dirs: + printTabSub(dir, 0) + + +##### MAIN + +tree = parseDir('.') +printTabWoMain(tree) + diff --git a/packaging/wrt-plugins-common.spec b/packaging/wrt-plugins-common.spec new file mode 100644 index 0000000..a9f645f --- /dev/null +++ b/packaging/wrt-plugins-common.spec @@ -0,0 +1,109 @@ +#git:framework/web/wrt-plugins-common +Name: wrt-plugins-common +Summary: wrt-plugins common library +Version: 0.3.132_w2 +Release: 1 +VCS: framework/web/wrt-plugins-common#submit/master/20130311.134353-36-gd21f1dd1a4093883baf25942eef0562263808726 +Group: Development/Libraries +License: Apache License, Version 2.0 +Source0: %{name}-%{version}.tar.gz + +BuildRequires: cmake +BuildRequires: pkgconfig(dpl-efl) +BuildRequires: pkgconfig(wrt-plugins-types) +BuildRequires: pkgconfig(security-client) +BuildRequires: pkgconfig(dpl-event-efl) +BuildRequires: pkgconfig(ewebkit2) +BuildRequires: pkgconfig(dpl-wrt-dao-ro) +BuildRequires: pkgconfig(dpl-wrt-dao-rw) +BuildRequires: pkgconfig(libpcrecpp) +BuildRequires: pkgconfig(icu-i18n) +BuildRequires: pkgconfig(libxml-2.0) +BuildRequires: pkgconfig(cert-svc-vcore) +BuildRequires: pkgconfig(wrt-commons-widget-interface-dao) +Requires: ldconfig + +%description +JavaScript plugins for WebRuntime + +%package devel +Summary: wrt-plugins-common library development headers +Group: Development/Libraries +Requires: %{name} = %{version} + +%description devel +wrt-plugins common library development headers + +%prep +%setup -q + +%define with_tests 0 +%if "%{WITH_TESTS}" == "ON" || "%{WITH_TESTS}" == "Y" || "%{WITH_TESTS}" == "YES" || "%{WITH_TESTS}" == "TRUE" || "%{WITH_TESTS}" == "1" + %define with_tests 1 +%endif + +%build +%if 0%{?sec_build_binary_debug_enable} +export CFLAGS="$CFLAGS -DTIZEN_DEBUG_ENABLE" +export CXXFLAGS="$CXXFLAGS -DTIZEN_DEBUG_ENABLE" +export FFLAGS="$FFLAGS -DTIZEN_DEBUG_ENABLE" +%endif + +%if "%{_repository}" == "wearable" +ln -s src_wearable src +%define device_profile "wearable" +%else +ln -s src_mobile src +%define device_profile "mobile" +%endif + +export LDFLAGS+="-Wl,--rpath=/usr/lib -Wl,--as-needed -Wl,--hash-style=both" + +cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \ + -DDPL_LOG="ON" \ + -DCMAKE_PROJECT_VERSION=%{version} \ + -DCMAKE_BUILD_TYPE=%{?build_type:%build_type} \ + -DDEVICE_PROFILE=%{?device_profile:%device_profile} \ + %{?WITH_TESTS:-DWITH_TESTS=%WITH_TESTS} +make %{?jobs:-j%jobs} + +%install +mkdir -p %{buildroot}/usr/share/license +cp LICENSE %{buildroot}/usr/share/license/%{name} +%make_install + +%clean +rm -rf %{buildroot} + +%post +mkdir -p %{_libdir}/wrt-plugins +mkdir -p /usr/etc/wrt/injected-javascript +touch /opt/share/widget/plugin-installation-required + +%files +%manifest wrt-plugins-common.manifest +/usr/etc/wrt-plugins/config.dtd +%{_libdir}/*.so +%{_libdir}/*.so.* +%{_libdir}/wrt-plugins/w3c-widget-interface/libwrt-plugins-w3c-widget-interface.so +%attr(755,root,root) %{_bindir}/wrt-popup-ace-runtime +%attr(755,root,root) %{_bindir}/wrt-popup-wrt-runtime +%attr(755,root,root) %{_bindir}/wrt-plugins-installer +%{_datadir}/license/%{name} +%if "%{_repository}" == "wearable" +/etc/smack/accesses2.d/wrt-popup-ace-runtime.rule +/etc/smack/accesses2.d/wrt-popup-wrt-runtime.rule +%else +/etc/smack/accesses2.d/wrt-popup-ace-runtime.mobile.rule +/etc/smack/accesses2.d/wrt-popup-wrt-runtime.mobile.rule +/opt/etc/smack/accesses.d/wrt-popup-ace-runtime.mobile2.rule +/opt/etc/smack/accesses.d/wrt-popup-wrt-runtime.mobile2.rule +%endif +%if %{with_tests} + %attr(755,root,root) %{_bindir}/widgetdb_tests_prepare_db.sh + %attr(755,root,root) %{_bindir}/wrt-plugins-common-tests-widgetdb +%endif + +%files devel +%{_includedir}/* +%{_libdir}/pkgconfig/* diff --git a/pkgconfigs/wrt-dispatch-event.pc.in b/pkgconfigs/wrt-dispatch-event.pc.in new file mode 100644 index 0000000..937bcaf --- /dev/null +++ b/pkgconfigs/wrt-dispatch-event.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/wrt-dispatch-event + +Name: wrt dispatch event support +Description: Support to dispatch DOM event +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl ewebkit2 +Libs: -L${libdir} -lwrt-dispatch-event +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugin-js-overlay.pc.in b/pkgconfigs/wrt-plugin-js-overlay.pc.in new file mode 100644 index 0000000..7b28b87 --- /dev/null +++ b/pkgconfigs/wrt-plugin-js-overlay.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +includedir=${prefix}/include/${project_name} + +Name: wrt-plugin-js-overlay +Description: header for enum value of supported custom js event types +Version: @CMAKE_PROJECT_VERSION@ +Requires: +Libs: +Cflags: -I${includedir}/js-overlay diff --git a/pkgconfigs/wrt-plugin-loading.pc.in b/pkgconfigs/wrt-plugin-loading.pc.in new file mode 100644 index 0000000..69b9f8f --- /dev/null +++ b/pkgconfigs/wrt-plugin-loading.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include + +Name: wrt-plugin-loading +Description: wrt-plugin-loading +Version: @PROJECT_VERSION@ +Requires: dpl-efl dpl-wrt-dao-ro ewebkit2 +Libs: -lwrt-plugin-loading -L${libdir} +Cflags: -I${includedir}/wrt-plugin-loading -I${includedir}/wrt-plugins-common diff --git a/pkgconfigs/wrt-plugins-api-support.pc.in b/pkgconfigs/wrt-plugins-api-support.pc.in new file mode 100644 index 0000000..579a085 --- /dev/null +++ b/pkgconfigs/wrt-plugins-api-support.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include + +Name: wrt-plugins-api-support +Description: wrt-plugins-api-support +Version: @PROJECT_VERSION@ +Requires: +Libs: -lwrt-plugins-api-support -L${libdir} +Cflags: -I${includedir}/wrt-plugins-api-support diff --git a/pkgconfigs/wrt-plugins-commons-javascript.pc.in b/pkgconfigs/wrt-plugins-commons-javascript.pc.in new file mode 100644 index 0000000..b522b22 --- /dev/null +++ b/pkgconfigs/wrt-plugins-commons-javascript.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WrtDeviceApis commons with JavaScrpt dependencies +Description: Commons for DeviceApis with JavaScrpt dependencies +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl ewebkit2 wrt-plugins-commons +Libs: -L${libdir} -lwrt-plugins-commons-javascript +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugins-commons.pc.in b/pkgconfigs/wrt-plugins-commons.pc.in new file mode 100644 index 0000000..e3c8c7a --- /dev/null +++ b/pkgconfigs/wrt-plugins-commons.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WrtDeviceApis commons +Description: Commons for DeviceApis +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl +Libs: -L${libdir} -lwrt-plugins-commons +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugins-filesystem.pc.in b/pkgconfigs/wrt-plugins-filesystem.pc.in new file mode 100644 index 0000000..49563e1 --- /dev/null +++ b/pkgconfigs/wrt-plugins-filesystem.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis Filesystem module +Description: WebRuntime Filesystem module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons +Libs: -L${libdir} -lwrt-plugins-filesystem +Cflags: -I${includedir}/Filesystem diff --git a/pkgconfigs/wrt-plugins-ipc-message.pc.in b/pkgconfigs/wrt-plugins-ipc-message.pc.in new file mode 100644 index 0000000..8088720 --- /dev/null +++ b/pkgconfigs/wrt-plugins-ipc-message.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt ipc message support +Description: Support IPC between plugins and UI Process +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl ewebkit2 +Libs: -L${libdir} -lwrt-plugins-ipc-message +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugins-plugin-manager.pc.in b/pkgconfigs/wrt-plugins-plugin-manager.pc.in new file mode 100644 index 0000000..c6a3faa --- /dev/null +++ b/pkgconfigs/wrt-plugins-plugin-manager.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis Plugin Manager module +Description: WebRuntime Plugin Manager module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons wrt-plugins-commons-javascript dpl-wrt-dao-ro ewebkit2 +Libs: -L${libdir} -lwrt-plugins-plugin-manager +Cflags: -I${includedir}/PluginManager diff --git a/pkgconfigs/wrt-plugins-widget-interface.pc.in b/pkgconfigs/wrt-plugins-widget-interface.pc.in new file mode 100644 index 0000000..8792516 --- /dev/null +++ b/pkgconfigs/wrt-plugins-widget-interface.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis Widget Interface module +Description: WebRuntime Widget Interface module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons dpl-wrt-dao-ro wrt-plugins-localstorage wrt-commons-widget-interface-dao +Libs: -L${libdir} -lwrt-plugins-widget-interface +Cflags: -I${includedir}/WidgetInterface diff --git a/pkgconfigs/wrt-plugins-widgetdb.pc.in b/pkgconfigs/wrt-plugins-widgetdb.pc.in new file mode 100644 index 0000000..788423a --- /dev/null +++ b/pkgconfigs/wrt-plugins-widgetdb.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib/ +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis WidgetDB module +Description: WebRuntime WidgetDB module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons +Libs: -L${libdir} -lwrt-plugins-widgetdb +Cflags: -I${includedir}/WidgetDB diff --git a/pkgconfigs/wrt-popup-ace-runner.pc.in b/pkgconfigs/wrt-popup-ace-runner.pc.in new file mode 100644 index 0000000..ad9605e --- /dev/null +++ b/pkgconfigs/wrt-popup-ace-runner.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt-popup-runner +Description: Library with function to run wrt runtime popup +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl dpl-dbus-efl elementary security-client +Libs: -L${libdir} -lwrt-popup-ace-runner +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-popup-runner.pc.in b/pkgconfigs/wrt-popup-runner.pc.in new file mode 100644 index 0000000..ad9605e --- /dev/null +++ b/pkgconfigs/wrt-popup-runner.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt-popup-runner +Description: Library with function to run wrt runtime popup +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl dpl-dbus-efl elementary security-client +Libs: -L${libdir} -lwrt-popup-ace-runner +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-popup-wrt-runner.pc.in b/pkgconfigs/wrt-popup-wrt-runner.pc.in new file mode 100644 index 0000000..a7b830f --- /dev/null +++ b/pkgconfigs/wrt-popup-wrt-runner.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt-popup-runner +Description: Library with function to run wrt runtime popup +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl +Libs: -L${libdir} -lwrt-popup-wrt-runner +Cflags: -I${includedir} diff --git a/src_mobile/CMakeLists.txt b/src_mobile/CMakeLists.txt new file mode 100644 index 0000000..ba7daa0 --- /dev/null +++ b/src_mobile/CMakeLists.txt @@ -0,0 +1,67 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Includes CMake configuration file (*.cmake), preserving appropriate paths. + +ADD_DEFINITIONS("-DWRT_PLUGINS_COMMON_LOG") + +macro(include_config_file INCLUDED_CONFIG_FILE_PATH) + get_filename_component(CURRENT_CONFIG_FILE_PATH ${CMAKE_CURRENT_LIST_FILE} PATH) + include(${CURRENT_CONFIG_FILE_PATH}/${INCLUDED_CONFIG_FILE_PATH}/${CONFIG_FILE_NAME} OPTIONAL) +endmacro() + +# Gets actual path for CMake configuration file (*.cmake). +# By default, if no argument is passed, current path will be set to variable +# named CURRENT_PATH. +# @param [Optional] Name of the variable to set with current path. +macro(get_current_path) + set(VARIABLE "CURRENT_PATH") + if (${ARGC} GREATER 0) + set(VARIABLE ${ARGV0}) + endif () + get_filename_component(${VARIABLE} ${CMAKE_CURRENT_LIST_FILE} PATH) +endmacro() + +set(HOST_ARCH $ENV{DEB_HOST_ARCH}) +if("${HOST_ARCH}" MATCHES "armel") + set(HOST_ARCH "armel") +endif() + +#target names +set(TARGET_PLUGIN_LOADING_LIB "wrt-plugin-loading") +set(TARGET_COMMONS "wrt-plugins-commons") +set(TARGET_COMMONS_JAVASCRIPT "wrt-plugins-commons-javascript") +set(TARGET_JS_OVERLAY "wrt-plugins-js-overlay") +SET(TARGET_POPUP_ACE "wrt-popup-ace-runtime") +SET(TARGET_POPUP_ACE_RUNNER_LIB "wrt-popup-ace-runner") +SET(TARGET_POPUP_WRT "wrt-popup-wrt-runtime") +SET(TARGET_POPUP_WRT_RUNNER_LIB "wrt-popup-wrt-runner") +set(TARGET_PLUGINS_API_SUPPORT "wrt-plugins-api-support") +set(TARGET_PLUGINS_IPC_MESSAGE_LIB "wrt-plugins-ipc-message") + +set(PLUGIN_LOADING_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugin-loading) +set(PLUGINS_API_SUPPORT_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins-api-support) +set(PLUGINS_IPC_MESSAGE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins-ipc-message) + +add_subdirectory(plugins-api-support) +add_subdirectory(plugin-loading) +add_subdirectory(js-overlay) +add_subdirectory(Commons) +add_subdirectory(CommonsJavaScript) +add_subdirectory(dispatch-event) +add_subdirectory(modules) +add_subdirectory(standards) +add_subdirectory(wrt-popup) +add_subdirectory(plugins-installer) +add_subdirectory(plugins-ipc-message) diff --git a/src_mobile/Commons/Base64.cpp b/src_mobile/Commons/Base64.cpp new file mode 100644 index 0000000..94ac901 --- /dev/null +++ b/src_mobile/Commons/Base64.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Copyright (c) 2003-2007, Bicom Systems Ltd. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of the Bicom Systems Ltd nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * Denis Komadaric, + * Bicom Systems Ltd. + */ +#include +#include "Exception.h" +#include "Base64.h" + +namespace WrtDeviceApis { +namespace Commons { +const std::string Base64::chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +bool Base64::is_base64(unsigned char c) +{ + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string Base64::encode(unsigned char* data, + std::size_t num) +{ + std::string ret; + int i = 0; + int j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (num--) { + char_array_3[i++] = *(data++); + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & + 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & + 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; i < 4; ++i) { + ret += chars[char_array_4[i]]; + } + i = 0; + } + } + + if (i != 0) { + for (j = i; j < 3; ++j) { + char_array_3[j] = '\0'; + } + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (j = 0; (j < i + 1); ++j) { + ret += chars[char_array_4[j]]; + } + + while ((i++ < 3)) { + ret += '='; + } + } + + return ret; +} + +std::string Base64::decode(const std::string& str) +{ + if (!is_base64_string(str)) { + ThrowMsg(InvalidArgumentException, + "Invalid length of base64 string."); + } + int in_len = str.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && (str[in_] != '=')) { + if (!is_base64(str[in_])) { + ThrowMsg(InvalidArgumentException, + "Invalid characters in base64 string."); + } + char_array_4[i++] = str[in_]; + in_++; + if (i == 4) { + for (i = 0; i < 4; ++i) { + char_array_4[i] = chars.find(char_array_4[i]); + } + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & + 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; i < 3; ++i) { + ret += char_array_3[i]; + } + i = 0; + } + } + + if (i != 0) { + for (j = i; j < 4; ++j) { + char_array_4[j] = 0; + } + + for (j = 0; j < 4; ++j) { + char_array_4[j] = chars.find(char_array_4[j]); + } + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (j = 0; (j < i - 1); ++j) { + ret += char_array_3[j]; + } + } + + return ret; +} + +bool Base64::is_base64_string(const std::string& str) +{ + return ((str.size() % 4) == 0); +} +} +} //WrtDeviceApisCommon diff --git a/src_mobile/Commons/Base64.h b/src_mobile/Commons/Base64.h new file mode 100644 index 0000000..5f42802 --- /dev/null +++ b/src_mobile/Commons/Base64.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_BASE64_H_ +#define WRTDEVICEAPIS_COMMONS_BASE64_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class Base64 +{ + public: + static std::string encode(unsigned char* data, + std::size_t num); + static std::string decode(const std::string& str); + + private: + static bool is_base64(unsigned char c); + static bool is_base64_string(const std::string& str); + + private: + static const std::string chars; +}; // Base64 +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_BASE64_H_ */ diff --git a/src_mobile/Commons/CMakeLists.txt b/src_mobile/Commons/CMakeLists.txt new file mode 100644 index 0000000..6b58193 --- /dev/null +++ b/src_mobile/Commons/CMakeLists.txt @@ -0,0 +1,106 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}) +endmacro() + +macro(install_wrtaccess_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}/WrtAccess) +endmacro() + +macro(install_widget_interface_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}/WidgetInterface) +endmacro() + +include_config_file(WrtAccess) + +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) +pkg_search_module(ace-client REQUIRED security-client) +pkg_search_module(dpl-event REQUIRED dpl-event-efl) +pkg_search_module(icu REQUIRED icu-i18n) + +set(WRT_COMMONS_DEPENDECIES_INCLUDES + ${wrt-plugin-api_INCLUDE_DIRS} + ${ace-client_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} + ${icu_INCLUDE_DIRS} + ) + +include_directories(${WRT_COMMONS_DEPENDECIES_INCLUDES}) + +set(TARGET_NAME ${TARGET_COMMONS}) + +set(SRCS + ${SRCS_WRT_ACCESS} + ${CMAKE_CURRENT_SOURCE_DIR}/Base64.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/FunctionDefinition.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Regex.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/RegexUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/StringBuilder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/StringUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ThreadPool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSObjectDeclaration.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSObject.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/TimeUtils.cpp + #PARENT_SCOPE +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${ace-client_LIBRARIES} + ${dpl-event_LIBRARIES} + ${icu_LIBRARIES} + ${TARGET_POPUP_ACE_RUNNER_LIB} +) + +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}) + +install_header_file(FunctionDeclaration.h) +install_header_file(FunctionDefinition.h) +install_header_file(Base64.h) +install_header_file(Deprecated.h) +install_header_file(Dimension.h) +install_header_file(Emitters.h) +install_header_file(EventListener.h) +install_header_file(EventReceiver.h) +install_header_file(Exception.h) +install_header_file(IEvent.h) +install_header_file(IExternEventCanceler.h) +install_header_file(ListenerEventEmitter.h) +install_header_file(ListenerEvent.h) +install_header_file(Range.h) +install_header_file(Regex.h) +install_header_file(RegexPatterns.h) +install_header_file(RegexUtils.h) +install_header_file(StaticAssert.h) +install_header_file(StringBuilder.h) +install_header_file(StringUtils.h) +install_header_file(ThreadPool.h) +install_header_file(TypesDeclaration.h) +install_header_file(TypeTraits.h) +install_header_file(plugin_initializer_def.h) +install_header_file(JSObjectDeclaration.h) +install_header_file(JSObject.h) +install_header_file(TimeUtils.h) +install_wrtaccess_header_file(WrtAccess/WrtAccess.h) diff --git a/src_mobile/Commons/DESCRIPTION b/src_mobile/Commons/DESCRIPTION new file mode 100644 index 0000000..7f04546 --- /dev/null +++ b/src_mobile/Commons/DESCRIPTION @@ -0,0 +1 @@ +Common code diff --git a/src_mobile/Commons/Deprecated.h b/src_mobile/Commons/Deprecated.h new file mode 100644 index 0000000..5db3acf --- /dev/null +++ b/src_mobile/Commons/Deprecated.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_DEPRECATED_H_ +#define WRTDEVICEAPIS_COMMONS_DEPRECATED_H_ + +#define WRT_PLUGINS_DEPRECATED __attribute__((deprecated)) + +#endif /* WRTDEVICEAPIS_COMMONS_DEPRECATED_H_ */ diff --git a/src_mobile/Commons/Dimension.h b/src_mobile/Commons/Dimension.h new file mode 100644 index 0000000..703e0c0 --- /dev/null +++ b/src_mobile/Commons/Dimension.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_DIMENSION_H_ +#define WRTDEVICEAPIS_COMMONS_DIMENSION_H_ + +namespace WrtDeviceApis { +namespace Commons { +/** + * Encapsulates width and height of a component. + */ +class Dimension +{ + public: + /** + * Type of dimension's values. + */ + typedef unsigned int ValueType; + + public: + /** + * Creates an instance of Dimension with specified width and height. + * @param width Specified width. + * @param height Specified height. + */ + Dimension(ValueType width, + ValueType height) : + m_width(width), + m_height(height) + {} + + ValueType getWidth() const + { + return m_width; + } + + ValueType getHeight() const + { + return m_height; + } + + void setSize(ValueType width, + ValueType height) + { + m_width = width; + m_height = height; + } + + private: + ValueType m_width; + ValueType m_height; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_DIMENSION_H_ diff --git a/src_mobile/Commons/Emitters.h b/src_mobile/Commons/Emitters.h new file mode 100644 index 0000000..7b1d8c2 --- /dev/null +++ b/src_mobile/Commons/Emitters.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_EMITTERS_H_ +#define WRTDEVICEAPIS_COMMONS_EMITTERS_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Manages listener events emitters. + * Template parameter should be class that derives from @see ListenerEvent. + */ +template +class Emitters +{ + public: + typedef EmitterClass EmitterType; + typedef DPL::SharedPtr EmitterPtrType; + typedef typename EmitterType::IdType EmitterIdType; + typedef typename EmitterType::EventType EventType; + typedef typename EmitterType::EventPtrType EventPtrType; + typedef std::auto_ptr LockType; + + public: + ~Emitters() + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_emitters.clear(); + } + + /** + * Attaches emitter. + * @param emitter Emitter. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + void attach(const EmitterPtrType& emitter) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_emitters[emitter->getId()] = emitter; + } + + /** + * Detaches emitter. + * @param id Id of an emitter. + * @return True when emitter was found and successfully detached, + * false otherwise. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + bool detach(const EmitterIdType id) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + return (m_emitters.erase(id) > 0); + } + + /** + * Emits event through all emitters. + * @param event Event to emit. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + void emit(const EventPtrType& event) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + for (Iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { + it->second->emit(event); + } + } + + /** + * Emits event through those emitters that when passed to predicate result + * in + * returning true by it. + * @param event Event to emit. + * @param pred Predicate - a callable object (function, functor) that takes + * an argument of type EmitterPtrType and returns boolean value. + */ + template + void emitIf(const EventPtrType& event, + Predicate pred) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + for (Iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { + if (bool(pred(it->second))) { + it->second->emit(event); + } + } + } + + /** + * Checks whether emitter of supplied id is attached. + * @param emitter Emitter. + * @return True when emitter has been found, false otherwise. + * @remarks Can be used within scope of getLock() call. + */ + bool isAttached(const EmitterIdType id) const + { + return (m_emitters.count(id) > 0); + } + + /** + * Returns number of attached emitters. + * @return Number of emitters. + * @remarks Can be used within scope of getLock() call. + */ + std::size_t size() const + { + return m_emitters.size(); + } + + /** + * Lock this object. + * This lock will be automatically released when out of scope (unless + * someone + * copies it). Do not use in the same scope as other API of this class. + * @return Lock object. + * @remarks Provided to allow locking emitters in scope of some client + * code. + */ + LockType getLock() + { + return LockType(new DPL::Mutex::ScopedLock(&m_mtx)); + } + + private: + typedef std::map Map; + typedef typename Map::iterator Iterator; + typedef typename Map::const_iterator ConstIterator; + + private: + DPL::Mutex m_mtx; ///< Synchronizes operation on this object. + Map m_emitters; ///< Emitters container. +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_EMITTERS_H_ diff --git a/src_mobile/Commons/EventListener.h b/src_mobile/Commons/EventListener.h new file mode 100644 index 0000000..f059082 --- /dev/null +++ b/src_mobile/Commons/EventListener.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ +#define WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Base class for listeners. + * Object that is to act as listener should dervie from this class and implement + * OnAnswerReceived() function. + */ +template +class EventListener : private EventReceiver +{ + public: + EventListener(ThreadEnum::Enumeration threadType) : + EventReceiver(threadType) + {} + + virtual void onAnswerReceived(const DPL::SharedPtr& event) = + 0; + + void postAnswer(const DPL::SharedPtr& event) + { + DPL::Event::ControllerEventHandler >:: + PostEvent( + event); + } + + protected: + void OnEventReceived(const DPL::SharedPtr &event) + { + onAnswerReceived(event); + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ */ diff --git a/src_mobile/Commons/EventReceiver.h b/src_mobile/Commons/EventReceiver.h new file mode 100644 index 0000000..3d7c67b --- /dev/null +++ b/src_mobile/Commons/EventReceiver.h @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ +#define WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +template +class SignalEventCall : public DPL::Event::AbstractEventCall +{ + DPL::SharedPtr m_event; + + public: + + SignalEventCall(const DPL::SharedPtr &event) : m_event(event) + {} + virtual void Call() + { + _D("signaling in SignalEventCall"); + m_event->signalSynchronousEventFlag(); + } +}; + +template +class EventReceiver : + protected DPL::Event::Controller< + typename DPL::TypeListDecl >::Type> +{ + DPL::Event::ThreadEventDispatcher m_threadDispatcher; + + protected: + + EventReceiver(ThreadEnum::Enumeration threadType) + { + DPL::Thread *thread = + ThreadPool::getInstance().getThreadRef(threadType); + DPL::Event::ControllerEventHandler >:: + Touch(); + DPL::Event::ControllerEventHandler >:: + SwitchToThread(thread); + } + + void signalEventByDispatcher(const DPL::SharedPtr &event) + { + _D("called"); + Try { + DPL::Event::AbstractEventDispatcher *dispatcher = + ThreadPool::getInstance().getDispatcher(m_threadDispatcher); + dispatcher->AddEventCall(new SignalEventCall(event)); + } + Catch(DPL::Thread::Exception::UnmanagedThread) { + // if called on unmanaged thread, + // call signalSynchronousEventFlag() directly + _E("signalSynchronousEventFlag() is called" + "by unmanaged thread"); + event->signalSynchronousEventFlag(); + } + } + + virtual ~EventReceiver() + { + DPL::Event::ControllerEventHandler >:: + SwitchToThread(NULL); + } +}; + +template +class EventRequestReceiver : private EventReceiver +{ + public: + EventRequestReceiver(ThreadEnum::Enumeration threadType) : EventReceiver< + TemplateEvent>(threadType) + {} + virtual void OnRequestReceived(const DPL::SharedPtr &event) + = 0; + + /* + * + * @argument delaySeconds - event will be received not sooner than after + * delay (in seconds) + */ + void PostRequest(const DPL::SharedPtr &event, + double delaySeconds = 0.0) + { + _D("called"); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + assert(TemplateEvent::STATE_INITIAL == event->m_state); + event->m_state = TemplateEvent::STATE_REQUEST_SEND; + } + + if (TemplateEvent::HANDLING_SYNCHRONOUS == event->getHandlingType() && + !event->m_synchronousEventFlag) + { + event->m_synchronousEventFlag = new DPL::WaitableEvent(); + } + + if (0.0 == delaySeconds) { + DPL::Event::ControllerEventHandler > + :: + PostEvent(event); + } else { + DPL::Event::ControllerEventHandler > + :: + PostTimedEvent(event, delaySeconds); + } + + switch (event->getHandlingType()) { + case TemplateEvent::HANDLING_NOT_SET: + assert(0); + break; + case TemplateEvent::HANDLING_SYNCHRONOUS: + event->waitForAnswer(); + break; + } + } + + void OnEventReceived(const DPL::SharedPtr &event) + { + _D("called"); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + if (event->m_cancelled) { + event->handleCancel(); + event->m_cancelAllowed = true; + event->signalCancelStatusFlag(); + event->signalFinishedFlag(); + return; + } else { + assert( + TemplateEvent::STATE_REQUEST_SEND == event->m_state && + "Wrong state!"); + } + event->m_state = TemplateEvent::STATE_REQUEST_RECEIVED; + } + + OnRequestReceived(event); + event->signalCancelStatusFlag(); + //After Controller ends processing it should call it to signal that work + // is done + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + + if (event->m_cancelled) { + //if cancel was not handled in OnRequestReceived when we should + //process as if it was not cancelled at all. + if (event->m_cancelAllowed) { + event->handleCancel(); + event->signalFinishedFlag(); + return; + } + } + //when event is not in manual answer mode we will answer now + if (TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER != + event->m_handlingType && + TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER != + event->m_handlingType) + { + event->m_state = TemplateEvent::STATE_ANSWER_SEND; + } + } + + switch (event->m_handlingType) { + case TemplateEvent::HANDLING_NOT_SET: + assert(0); + break; + case TemplateEvent::HANDLING_SYNCHRONOUS: + //event->Signal(); + this->signalEventByDispatcher(event); + break; + case TemplateEvent::HANDLING_ASYNCHRONOUS: + ///TODO check - shouldn't it be in signalEventByDispatcher? + if (NULL != event->m_remoteController) { + event->m_remoteController->PostAnswer(event); + } + //event->Signal(); + this->signalEventByDispatcher(event); + break; + //when event is in manual answer mode we do nothing - the answer will be + // send explicit from the code + case TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER: + case TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER: + break; + } + } + + virtual void ManualAnswer(const DPL::SharedPtr &event) + { + _D("called"); + assert( + event->m_handlingType == + TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER || + event->m_handlingType == + TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + if (event->m_cancelled) { + //if cancel was not handled in OnRequestReceived when we should + //process as if it was not cancelled at all. + if (event->m_cancelAllowed) { + event->handleCancel(); + event->signalCancelStatusFlag(); + event->signalFinishedFlag(); + return; + } + } + event->m_state = TemplateEvent::STATE_ANSWER_SEND; + } + switch (event->m_handlingType) { + case TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER: + //event->Signal(); + this->signalEventByDispatcher(event); + break; + case TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER: + //event->Signal(); + if (NULL != event->m_remoteController) { + event->m_remoteController->PostAnswer(event); + } + this->signalEventByDispatcher(event); + break; + default: + break; + } + } +}; + +template +class EventAnswerReceiver : private EventReceiver +{ + public: + EventAnswerReceiver(ThreadEnum::Enumeration threadType) : EventReceiver< + TemplateEvent>(threadType) + {} + + virtual void OnAnswerReceived(const DPL::SharedPtr &event) = + 0; + + //it should be hidden outside, but I can't do it! I can't! :| + void PostAnswer(const DPL::SharedPtr &event) + { + LogDebug(__FUNCTION__); + event->signalCancelStatusFlag(); + DPL::Event::ControllerEventHandler >:: + PostEvent( + event); + } + + void OnEventReceived(const DPL::SharedPtr &event) + { + _D("EventAnswerReceiver: answer received"); + //check if it can be processed and set the state + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + + //in case someone changed it to synchronous call, we don't process + // it + if (TemplateEvent::STATE_CHANGED_TO_SYNCHRONOUS == + event->m_state || TemplateEvent::STATE_ENDED == + event->m_state) + { + return; + } + //we should get cancelled or answer_send state here + assert( + TemplateEvent::STATE_ANSWER_SEND == event->m_state && + "Wrong state!"); + + if (event->m_cancelled && event->m_cancelAllowed) { + event->handleCancel(); + event->signalFinishedFlag(); + return; + } + event->m_state = TemplateEvent::STATE_ANSWER_RECEIVED; + } + + OnAnswerReceived(event); + + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + assert(TemplateEvent::STATE_ANSWER_RECEIVED == event->m_state); + event->m_state = TemplateEvent::STATE_ENDED; + delete event->m_cancelStatusFlag; + event->m_cancelStatusFlag = NULL; + //if someone is waiting + event->signalFinishedFlag(); + } + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ */ diff --git a/src_mobile/Commons/Exception.h b/src_mobile/Commons/Exception.h new file mode 100644 index 0000000..0f1db99 --- /dev/null +++ b/src_mobile/Commons/Exception.h @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ +#define WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +#define PLUGINS_DECLARE_EXCEPTION_TYPE(BaseClass, Class) \ + class Class : \ + public BaseClass \ + { \ + ExceptionCodes::Enumeration m_code; \ + public: \ + virtual ExceptionCodes::Enumeration getCode() const { return m_code; } \ + Class(const char *path, \ + const char *function, \ + int line, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, message) \ + { \ + BaseClass::m_className = #Class; \ + m_code = ExceptionCodes::Class; \ + } \ + \ + Class(const char *path, \ + const char *function, \ + int line, \ + const DPL::Exception & reason, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, reason, message) \ + { \ + BaseClass::m_className = #Class; \ + m_code = ExceptionCodes::Class; \ + } \ + }; + +class ExceptionCodes +{ + public: + enum Enumeration + { + None, + Exception, + InvalidArgumentException, + ConversionException, + NullPointerException, + UnknownException, + PlatformException, + OutOfRangeException, + EventCancelledException, + EventWrongStateException, + SecurityException, + UnsupportedException, + PlatformWrongStateException, + PendingOperationException, + AlreadyInUseException, + CameraCaptureException, + CameraLiveVideoException, + LocalStorageValueNoModifableException, + NotFoundException + }; +}; + +/** + * General exception. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(DPL::Exception, Exception) + +/** + * Thrown when passed argument is not of expected type. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, InvalidArgumentException) + +/** + * Thrown when type conversion is not possible. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, ConversionException) + +/** + * Thrown when trying to operate on an object which is set to NULL. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, NullPointerException) + +/** + * Thrown when unknown error occured. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, UnknownException) + +/** + * Thrown when platform function returned error code or threw an exception. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PlatformException) + +/** + * Thrown when trying to access out of range element from array + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, OutOfRangeException) + +/** + * Thrown when trying to operate on cancelled event + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, EventCancelledException) + +/** + * Thrown when trying to operate on event in wrong state + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, EventWrongStateException) + +/** + * Thrown when trying to perform some action w/o proper permissions. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, SecurityException) + +/** + * Thrown when trying to perform action that is not supported by current + * platform. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, UnsupportedException) + +/** + * Thrown when trying to perform action on platform in wrong state. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PlatformWrongStateException) + +/** + * Thrown when trying to perform asynchronous action on JS object + * that already executes other asynchronous operation. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PendingOperationException) + +/** + * Thrown when used camera is already in use. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, AlreadyInUseException) + +/** + * Thrown when unpredicted error occurs while a picture or video is being + * captured + * or if endRecording is called while no video is currently captured. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, CameraCaptureException) + +/** + * camera live video cannot be provided. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, CameraLiveVideoException) + +/** + * Error trying to modify read only value + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, LocalStorageValueNoModifableException) + +/** + * Thrown when object is not found. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, NotFoundException) +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ */ diff --git a/src_mobile/Commons/FunctionDeclaration.h b/src_mobile/Commons/FunctionDeclaration.h new file mode 100644 index 0000000..d603c49 --- /dev/null +++ b/src_mobile/Commons/FunctionDeclaration.h @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARATION_ +#define WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARATION_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define ACE_DECLARE_FUNCTION(function_definition) \ + extern WrtDeviceApis::Commons::AceFunction ace_##function_definition + +#define ACE_DECLARE_PARAM(param_definition) \ + extern WrtDeviceApis::Commons::AceDeviceCapParam ace_param_## \ + param_definition + +class DevCapFinder +{ + public: + explicit DevCapFinder(const std::string& devcap) : m_searchFor(devcap) + {} + explicit DevCapFinder(const char* devcap) : m_searchFor(devcap) + {} + bool operator()(const WrtDeviceApis::Commons::AceDeviceCapability& dc) + const + { + return m_searchFor == dc.devCapName; + } + + private: + std::string m_searchFor; +}; + +#define ACE_ADD_DEV_CAP_PARAM(dev_caps_list, dev_cap_name, param) \ + do { \ + WrtDeviceApis::Commons::AceDeviceCaps::iterator devcapit = \ + std::find_if(dev_caps_list.begin(), \ + dev_caps_list.end(), \ + DevCapFinder(dev_cap_name)); \ + if (devcapit == dev_caps_list.end()) \ + { \ + ThrowMsg( \ + WrtDeviceApis::Commons::InvalidArgumentException, \ + "Trying to set a param that doesn't exist: " << \ + dev_cap_name); \ + } \ + else \ + { \ + LogDebug("Setting dev cap " << dev_cap_name << " param: " << \ + param.name << " to value " << param.value); \ + devcapit->devCapParams.push_back(param); \ + } \ + } while (0) + +/* + * Macro must be run inside plugin function. Plugin function must follow this + * declaration: + * plugin_example_function(JScontextRef cotext, JSObjectRef function, + * JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + * JSValueRef *exception); + * where context, arguments, argumentsCount, exception are fixed and could not + * be change. + * */ + +#define DECLARE_FUNCTION_GETTER(Plugin_Module) \ + WrtDeviceApis::Commons::AceFunction get##Plugin_Module##FunctionData( \ + const std::string & functionId); + +#define DEFINE_FUNCTION_GETTER(Plugin_Module, FunctionMap) \ + WrtDeviceApis::Commons::AceFunction get##Plugin_Module##FunctionData( \ + const std::string & functionId) \ + { \ + WrtDeviceApis::Commons::FunctionMapping::const_iterator it = \ + FunctionMap.find(functionId); \ + if (it == FunctionMap.end()) \ + { \ + std::string errorMsg(); \ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, \ + "Function with id " << functionId << "not found"); \ + } \ + return it->second; \ + } + +typedef WrtDeviceApis::Commons::AceFunction (&AceFunctionGetter)(const std:: + string&); + +namespace WrtDeviceApis { +namespace Commons { +enum class AceSecurityStatus +{ + AccessGranted, + AccessDenied, + PrivacyDenied, + InternalError +}; + +template +class DefaultArgsVerifier +{ + public: + void operator()(AceFunction& aceFunction, Args && ... args) const + { + static_assert( + WrtDeviceApis::Commons::AlwaysFalse::value, + "Please provide a specialization for these argument types!"); + } +}; + +template <> +class DefaultArgsVerifier<> +{ + public: + void operator()(AceFunction& /*aceFunction*/) const + {} +}; + +template +AceSecurityStatus aceCheckAccess( + const FunctionGetter& f, + const char* functionName, + Args && ... args) +{ + using namespace WrtDeviceApis::Commons; + + AceFunction aceFunction = f(functionName); + + ArgumentsVerifier argsVerify; + argsVerify(aceFunction, args ...); + + WrtAccess::CheckAccessReturnType ret = + WrtAccessSingleton::Instance().checkAccessControl(aceFunction); + + if (ret == WrtAccess::CHECK_ACCESS_PRIVILEGE_DENIED) { + return AceSecurityStatus::AccessDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_PRIVACY_DENIED) { + return AceSecurityStatus::PrivacyDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_INTERNAL_ERROR) { + return AceSecurityStatus::InternalError; + } + + return AceSecurityStatus::AccessGranted; +} +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARARION_ diff --git a/src_mobile/Commons/FunctionDefinition.cpp b/src_mobile/Commons/FunctionDefinition.cpp new file mode 100644 index 0000000..4209994 --- /dev/null +++ b/src_mobile/Commons/FunctionDefinition.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "FunctionDefinition.h" + +namespace WrtDeviceApis { +namespace Commons { +int aceAddDeviceCap(const AceDeviceCapability& cap, + AceDeviceCaps &instance) +{ + instance.push_back(cap); + return 0; +} + +int aceAddApiFeature(const AceFeature& apiFeature, + AceFeatures& instance) +{ + instance.push_back(apiFeature); + return 0; +} +} +} // WrtDeviceApisCommon diff --git a/src_mobile/Commons/FunctionDefinition.h b/src_mobile/Commons/FunctionDefinition.h new file mode 100644 index 0000000..fa8b32c --- /dev/null +++ b/src_mobile/Commons/FunctionDefinition.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION_ +#define WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Creates an empty device cap list. Additional device-caps may be added by + * ACE_CREATE_DEVICE_CAP and ACE_ADD_DEVICE_CAP macros + */ +#define ACE_CREATE_DEVICE_CAPS_LIST(device) \ + WrtDeviceApis::Commons::AceDeviceCaps ace_##device + +/** + * Creates an empty api features list. Additional api features may be added by + * ACE_CREATE_FEATURE and ACE_ADD_API_FEATURE macros + */ +#define ACE_CREATE_FEATURE_LIST(apifeature) \ + WrtDeviceApis::Commons::AceFeatures ace_##apifeature + +/** + * Creates a device capability which should be later added to device cap list + */ +#define ACE_CREATE_DEVICE_CAP(device_cap_id, cap_id) \ + WrtDeviceApis::Commons::AceDeviceCapability ace_##device_cap_id = \ + AceDeviceCapability(cap_id, WrtDeviceApis::Commons::AceDeviceCapParams()); + +/** + * Create an api feature which should be later added to api features list + */ +#define ACE_CREATE_FEATURE(feature_id, feature_api) \ + WrtDeviceApis::Commons::AceFeature ace_##feature_id = { feature_api \ + }; + +/** + * Adds an existing device-cap created by ACE_CREATE_DEVICE_CAP macro to + * device cap list + */ +#define ACE_ADD_DEVICE_CAP(device, device_cap_id) \ + WrtDeviceApis::Commons::aceAddDeviceCap(ace_##device_cap_id, ace_##device) + +/** + * Adds an existing api feature created by ACE_CREATE_FEATURE macro to + * api feature list + */ +#define ACE_ADD_API_FEATURE(apifeature, feature_id) \ + WrtDeviceApis::Commons::aceAddApiFeature(ace_##feature_id, \ + ace_##apifeature) + +/** + * Creates a function definition with given id that uses provided api feature + * and device capability lists + */ +#define ACE_CREATE_FUNCTION(function_id, function_name, feature_id, device) \ + { function_name, ace_##feature_id, ace_##device } + +// Support for param:name begin +#define ACE_CREATE_PARAM(param_definition, param_name, position) \ + static WrtDeviceApis::Commons::AceDeviceCapParam ace_param_## \ + param_definition = \ + { std::string(param_name), position }; + +// Support for param:name end + +typedef std::map FunctionMapping; + +int aceAddDeviceCap(const AceDeviceCapability &cap, + AceDeviceCaps & instance); +int aceAddApiFeature(const AceFeature &apiFeature, + AceFeatures & instance); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION diff --git a/src_mobile/Commons/IEvent.h b/src_mobile/Commons/IEvent.h new file mode 100644 index 0000000..207f5bb --- /dev/null +++ b/src_mobile/Commons/IEvent.h @@ -0,0 +1,383 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_IEVENT_H_ +#define WRTDEVICEAPIS_COMMONS_IEVENT_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class IEventPrivateData +{ + public: + virtual ~IEventPrivateData() + {} +}; + +class IEventController +{ + DPL::SharedPtr m_privateData; + + public: + virtual void waitTillProcessed() = 0; + virtual void waitForAnswer() = 0; + virtual bool cancelRequest() + { + return false; + } + virtual bool changeCallToSynchronous() = 0; + virtual ~IEventController() + {} + + void setPrivateData( + const DPL::SharedPtr &privateData) + { + m_privateData = privateData; + } + const DPL::SharedPtr& getPrivateData() + { + return m_privateData; + } +}; +typedef DPL::SharedPtr IEventControllerPtr; + +// CRTP pattern +template +class IEvent : /*private DPL::WaitableEvent, */ public IEventController +{ + public: + friend class EventRequestReceiver; + friend class EventAnswerReceiver; + friend class SignalEventCall; + friend class EventReceiver; + + enum HandlingType + { + HANDLING_NOT_SET = -1, + HANDLING_SYNCHRONOUS = 0, + HANDLING_ASYNCHRONOUS = 1, + HANDLING_SYNCHRONOUS_MANUAL_ANSWER = 2, + HANDLING_ASYNCHRONOUS_MANUAL_ANSWER = 3 + }; + + enum State + { + STATE_INITIAL, + STATE_REQUEST_SEND, + STATE_REQUEST_RECEIVED, + STATE_ANSWER_SEND, + STATE_ANSWER_RECEIVED, + STATE_ENDED, + STATE_CHANGED_TO_SYNCHRONOUS + }; + + private: + void handleCancel() + { + clearOnCancel(); + m_state = STATE_ENDED; + m_exceptionCode = Commons::ExceptionCodes::EventCancelledException; + //if someone is waiting + signalSynchronousEventFlag(); + } + + protected: + DPL::Mutex m_stateMutex; + State m_state; + HandlingType m_handlingType; + EventAnswerReceiver< Super > *m_remoteController; + Commons::ExceptionCodes::Enumeration m_exceptionCode; + DPL::WaitableEvent *m_synchronousEventFlag; + DPL::WaitableEvent *m_finishedFlag; + DPL::WaitableEvent *m_cancelStatusFlag; + bool m_cancelSignalAhead; + bool m_cancelled; + bool m_cancelAllowed; + + IEvent() : + m_state(STATE_INITIAL), + m_handlingType(HANDLING_NOT_SET), + m_remoteController(NULL), + m_exceptionCode(Commons::ExceptionCodes::None), + m_synchronousEventFlag(NULL), + m_finishedFlag(NULL), + m_cancelStatusFlag(NULL), + m_cancelSignalAhead(false), + m_cancelled(false), + m_cancelAllowed(false) + {} + + virtual void waitForAnswer() + { + assert(HANDLING_SYNCHRONOUS == m_handlingType); + DPL::WaitForSingleHandle(m_synchronousEventFlag->GetHandle()); + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + m_state = STATE_ENDED; + } + signalFinishedFlag(); + LogDebug("deleting m_processEvent"); + delete m_synchronousEventFlag; + m_synchronousEventFlag = NULL; + } + + void signalFinishedFlag() + { + if (m_finishedFlag) { + m_finishedFlag->Signal(); + } + } + + DPL::WaitableEvent &getFinishedFlag() + { + if (!m_finishedFlag) { + m_finishedFlag = new DPL::WaitableEvent(); + } + return *m_finishedFlag; + } + + void signalCancelStatusFlag() + { + LogDebug("signaling cancel"); + DPL::Mutex::ScopedLock lock(&m_stateMutex); + m_cancelSignalAhead = true; + if (m_cancelStatusFlag) { + m_cancelStatusFlag->Signal(); + } + } + + DPL::WaitableEvent &getCancelStatusFlag() + { + if (!m_cancelStatusFlag) { + m_cancelStatusFlag = new DPL::WaitableEvent(); + } + return *m_cancelStatusFlag; + } + + void signalSynchronousEventFlag() + { + if (m_synchronousEventFlag) { + m_synchronousEventFlag->Signal(); + } + } + + public: + + /* + * Gets the answer receiver pointer. + */ + EventAnswerReceiver< Super > * getAnswerReceiverRef() const + { + return m_remoteController; + } + + virtual ~IEvent() + { + delete m_cancelStatusFlag; + delete m_finishedFlag; + delete m_synchronousEventFlag; + } + + virtual bool changeCallToSynchronous() + { + return setForSynchronousCall(); + } + + virtual void waitTillProcessed() + { + DPL::WaitForSingleHandle(getFinishedFlag().GetHandle()); + delete m_finishedFlag; + m_finishedFlag = NULL; + } + + virtual void clearOnCancel() + {} + + Commons::ExceptionCodes::Enumeration getExceptionCode() const + { + return m_exceptionCode; + } + void setExceptionCode(Commons::ExceptionCodes::Enumeration exceptionCode) + { + m_exceptionCode = exceptionCode; + } + + short getHandlingType() const + { + return m_handlingType; + } + + virtual bool setForSynchronousCall() + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + m_state = STATE_CHANGED_TO_SYNCHRONOUS; + break; + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + m_handlingType = HANDLING_SYNCHRONOUS; + return true; + } + + virtual bool setForAsynchronousCall( + EventAnswerReceiver< Super > *remoteController) + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + m_handlingType = HANDLING_ASYNCHRONOUS; + m_remoteController = remoteController; + return true; + } + + /* + * Normally, after invoking OnRequestReceived in RequestReceiver, the answer + * is being send automatically (after flow leaves OnRequestReceived). + * After calling this function, the answer is not being send automatically, + * you need to call ManualAnswer to send event back. + * It works both in asynchronous and synchronous handling type. + */ + virtual bool switchToManualAnswer() + { + assert( + m_handlingType == HANDLING_ASYNCHRONOUS || m_handlingType == + HANDLING_SYNCHRONOUS); + + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + + switch (m_handlingType) { + case HANDLING_ASYNCHRONOUS: + m_handlingType = HANDLING_ASYNCHRONOUS_MANUAL_ANSWER; + break; + case HANDLING_SYNCHRONOUS: + m_handlingType = HANDLING_SYNCHRONOUS_MANUAL_ANSWER; + break; + default: + break; + } + return true; + } + + bool checkCancelled() + { + //DPL::Mutex::ScopedLock lock(&m_stateMutex); + return m_cancelled; + } + + void tryCancelled() + { + //DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + Throw(Commons::EventCancelledException); + } + } + + bool getCancelAllowed() const + { + return m_cancelAllowed; + } + + void setCancelAllowed(bool cancelAllowed) + { + m_cancelAllowed = cancelAllowed; + } + + bool cancelRequest() + { + LogDebug("trying to cancel"); + assert(HANDLING_ASYNCHRONOUS == m_handlingType || + HANDLING_ASYNCHRONOUS_MANUAL_ANSWER == m_handlingType); + bool signaled = false; + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_INITIAL: + assert(0); + case STATE_ANSWER_SEND: + LogDebug("cancelling"); + m_cancelled = true; + delete m_cancelStatusFlag; + m_cancelStatusFlag = NULL; + return m_cancelAllowed; + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + LogDebug("cancelling"); + m_cancelled = true; + signaled = m_cancelSignalAhead; + if (!signaled) { + //create waitable handle + getCancelStatusFlag(); + } + } + LogDebug("waiting for cancel flag"); + if (!signaled) { + DPL::WaitForSingleHandle(getCancelStatusFlag().GetHandle()); + } + delete m_cancelStatusFlag; + m_cancelStatusFlag = NULL; + return m_cancelAllowed; + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_IEVENT_H_ */ diff --git a/src_mobile/Commons/IExternEventCanceler.h b/src_mobile/Commons/IExternEventCanceler.h new file mode 100644 index 0000000..5a7a7e0 --- /dev/null +++ b/src_mobile/Commons/IExternEventCanceler.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ +#define WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * This class is related to JSPendingOperation object. + * + * It is interface for controllers which want to perform + * an additional accation when the PendingOberation object + * is canceled. + * */ +template +class IExternEventCanceler +{ + public: + virtual void OnCancelEvent(const DPL::SharedPtr& event) = 0; + + virtual ~IExternEventCanceler() + {} +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ diff --git a/src_mobile/Commons/JSObject.cpp b/src_mobile/Commons/JSObject.cpp new file mode 100644 index 0000000..70488f1 --- /dev/null +++ b/src_mobile/Commons/JSObject.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "JSObject.h" +#include + +JSObject::JSObject(RealObject object) : m_object(object) +{ + if (!object) { + LogError("Object is NULL"); + } +} + +JSObject::RealObject JSObject::getObject() const +{ + return m_object; +} diff --git a/src_mobile/Commons/JSObject.h b/src_mobile/Commons/JSObject.h new file mode 100644 index 0000000..d52f5a8 --- /dev/null +++ b/src_mobile/Commons/JSObject.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_H_ + +#include +#include + +class JSObject : private DPL::Noncopyable +{ + public: + typedef void* RealObject; + + public: + explicit JSObject(RealObject object); + + /** + * returns javascript engine object + * @throw NullPtrException + * */ + virtual RealObject getObject() const; + + virtual ~JSObject() + {} + + private: + RealObject m_object; +}; + +typedef DPL::SharedPtr JSObjectPtr; + +#endif diff --git a/src_mobile/Commons/JSObjectDeclaration.cpp b/src_mobile/Commons/JSObjectDeclaration.cpp new file mode 100755 index 0000000..81578cc --- /dev/null +++ b/src_mobile/Commons/JSObjectDeclaration.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object_declaration.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include "JSObjectDeclaration.h" + +JSObjectDeclaration::JSObjectDeclaration(js_entity_definition_ptr_t classD) : + m_name(classD->object_name), + m_parentName(classD->parent_name), + m_interfaceName(classD->interface_name), + m_classTemplate(NULL), + m_constructorCallback(classD->js_class_constructor_cb) +{ + if (NULL != classD->js_class_template_getter_fun) { + m_classTemplate = classD->js_class_template_getter_fun(); + } + if (classD->class_options) { + m_options = OptionsPtr(new Options(classD->class_options)); + } +} + +JSObjectDeclaration::~JSObjectDeclaration() +{} + +bool JSObjectDeclaration::checkIframesSupported() const +{ + if (!m_options || + m_options->getIframeObject() == Options::IFrameObject::None) + { + return false; + } + + return true; +} + +JSObjectDeclaration::Options::ClassType +JSObjectDeclaration::Options::getType() const +{ + Assert(m_options && "Pointer to options is NULL"); + + switch (m_options->type) { + case JS_CLASS: return ClassType::Class; + case JS_FUNCTION: return ClassType::Function; + case JS_INTERFACE: return ClassType::Interface; + default: Assert(0 && "Wrong value of type"); + } +} + +JSObjectDeclaration::Options::IFrameObject +JSObjectDeclaration::Options::getIframeObject() const +{ + Assert(m_options && "Options object is NULL"); + + switch (m_options->iframe_option) { + case NONE: return IFrameObject::None; + case REFERENCE: return IFrameObject::Reference; // deprecated + case CREATE_INSTANCE: return IFrameObject::CreateInstance; + default: + Assert(0 && "Wrong value of behaviour type"); + } +} + +JSObjectDeclaration::Options::IFrameNotice +JSObjectDeclaration::Options::getIframeNotice() const +{ + Assert(m_options && "Pointer to options is null"); + + switch (m_options->iframe_notice) { + case NONE_NOTICE: return IFrameNotice::None; + case ALWAYS_NOTICE: return IFrameNotice::AlwaysNotice; + default: + Assert(0 && "Wrong value of notice option"); + } +} + +js_function_impl JSObjectDeclaration::Options::getFunctionImpl() const +{ + Assert(m_options && "Pointer to options is null"); + return m_options->function; +} + +void JSObjectDeclaration::Options::invokeCallback(JsContext ctx, + ObjectInstance iframe, + ObjectInstance object) const +{ + LogDebug("JS Object create, notice."); + Assert(m_options && m_options->cb && "Empty callback pointer"); + m_options->cb(ctx, iframe, object); +} + +JSObjectDeclaration::Options::PrivateData +JSObjectDeclaration::Options::getPrivateData() const +{ + Assert(m_options && m_options->private_data && "empty private data"); + return m_options->private_data; +} diff --git a/src_mobile/Commons/JSObjectDeclaration.h b/src_mobile/Commons/JSObjectDeclaration.h new file mode 100644 index 0000000..a726029 --- /dev/null +++ b/src_mobile/Commons/JSObjectDeclaration.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object_declaration.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_DECLARATION_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_DECLARATION_H_ + +#include +#include +#include +#include +#include +#include +#include + +class JSObjectDeclaration : private DPL::Noncopyable +{ + public: + typedef const void* ConstClassTemplate; + typedef void* ClassTemplate; + typedef js_class_constructor_cb_t ConstructorCallback; + typedef class_definition_options_t ClassOptions; + + class Options : DPL::Noncopyable + { + public: + enum class ClassType + { + Class, + Function, + Interface + }; + + enum class IFrameObject + { + None, + Reference, + CreateInstance + }; + + enum class IFrameNotice + { + None, + AlwaysNotice + }; + + //only for function + enum class IFrameOverlay + { + Ignored, + UseOverlayed, //deprecated + OverlayedBeforeOriginal //deprecated + }; + + typedef js_object_instance_t ObjectInstance; + typedef java_script_context_t JsContext; + typedef void* PrivateData; + + public: + ClassType getType() const; + + IFrameObject getIframeObject() const; + IFrameNotice getIframeNotice() const; + js_function_impl getFunctionImpl() const; + + void invokeCallback(JsContext ctx, + ObjectInstance iframe, + ObjectInstance object) const; + + PrivateData getPrivateData() const; + + private: + const ClassOptions* m_options; + + private: + explicit Options(const ClassOptions* options) : m_options(options) + { + assert(options && "Dont create empty options"); + } + + friend class JSObjectDeclaration; + }; + + typedef std::shared_ptr OptionsPtr; + + public: + + explicit JSObjectDeclaration(js_entity_definition_ptr_t declaration); + + virtual const std::string& getName() const + { + return m_name; + } + + virtual const std::string& getParentName() const + { + return m_parentName; + } + + virtual ConstClassTemplate getClassTemplate() const + { + return m_classTemplate; + } + + virtual const std::string& getInterfaceName() const + { + return m_interfaceName; + } + + virtual ConstructorCallback getConstructorCallback() const + { + return m_constructorCallback; + } + + const OptionsPtr getOptions() const + { + return m_options; + } + + bool checkIframesSupported() const; + + virtual ~JSObjectDeclaration(); + + private: + std::string m_name; + std::string m_parentName; + std::string m_interfaceName; + ConstClassTemplate m_classTemplate; + ConstructorCallback m_constructorCallback; + OptionsPtr m_options; +}; + +typedef DPL::SharedPtr JSObjectDeclarationPtr; + +#endif diff --git a/src_mobile/Commons/ListenerEvent.h b/src_mobile/Commons/ListenerEvent.h new file mode 100644 index 0000000..7956ab7 --- /dev/null +++ b/src_mobile/Commons/ListenerEvent.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ +#define WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +template +class ListenerEventEmitter; + +/** + * This is base class for events that should act as signals between abstract + * layer and layer that uses it (e.g. JS layer in WRT plugins). + * Such event is created by specific event emitter from abstract layer + * and passed asynchronously to object that acts as event listener. + * Template parameter should be class of an event which derives from + * this class (co called CRTP pattern). + */ +template +class ListenerEvent +{ + friend class ListenerEventEmitter; + + public: + typedef IEventPrivateData PrivateDataType; + typedef DPL::SharedPtr PrivateDataTypePtr; + + public: + virtual ~ListenerEvent() + { + delete m_mtx; + } + + /** + * Gets exception code. + * @return Exception code. + */ + Commons::ExceptionCodes::Enumeration getExceptionCode() const + { + DPL::Mutex::ScopedLock lock(m_mtx); + return m_code; + } + + /** + * Sets exception code. + * @param code Exception code. + * @throw EventWrongStateExeption When event has already been emitted. + */ + void setExceptionCode(Commons::ExceptionCodes::Enumeration code) + { + DPL::Mutex::ScopedLock lock(m_mtx); + m_code = code; + } + + /** + * Gets event's private data. + * @return Private data (use DPL cast to proper object). + */ + const PrivateDataTypePtr& getPrivateData() const + { + DPL::Mutex::ScopedLock lock(m_mtx); + return m_privateData; + } + + protected: + ListenerEvent() : + m_mtx(new DPL::Mutex()), + m_code(Commons::ExceptionCodes::None) + {} + + ListenerEvent(const ListenerEvent &ths) : + m_mtx(new DPL::Mutex()), + m_code(ths.m_code), + m_privateData(ths.m_privateData) + {} + + ListenerEvent& operator=(const ListenerEvent &other) + { + if (this != &other) { + m_mtx = new DPL::Mutex(); + m_code = other.m_code; + m_privateData = other.m_privateData; + } + return *this; + } + + /** + * Sets event's private data. + * Event's private data object has to implement @see IEventPrivateData + * interface. + * @param data Private data. + * @throw EventWrongStateExeption When event has already been emitted. + */ + void setPrivateData(const PrivateDataTypePtr& data) + { + DPL::Mutex::ScopedLock lock(m_mtx); + m_privateData = data; + } + + protected: + mutable DPL::Mutex *m_mtx; + Commons::ExceptionCodes::Enumeration m_code; ///< Exception code. + PrivateDataTypePtr m_privateData; ///< Private data. +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ diff --git a/src_mobile/Commons/ListenerEventEmitter.h b/src_mobile/Commons/ListenerEventEmitter.h new file mode 100644 index 0000000..77bada2 --- /dev/null +++ b/src_mobile/Commons/ListenerEventEmitter.h @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ +#define WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +template +class Emitters; + +/** + * Creates listener events in the abstraction layer in response to some + * asynchronous action. + * To enable passing events from abstract layer to layer that uses it, first + * proper event emitter should be registered in abstract layer by the layer + * that uses it. Then when some action happens in abstract layer event should be + * created and passed to this emitter's emit() function. Then emitter passes + * this event to proper listener. + * Template parameter should be class that derives from @see ListenerEvent. + */ +template +class ListenerEventEmitter : private DPL::Noncopyable +{ + public: + typedef EventClass EventType; + typedef DPL::SharedPtr EventPtrType; + typedef ListenerEventEmitter Type; + typedef typename ListenerEvent::PrivateDataType + EventPrivateDataType; + typedef typename ListenerEvent::PrivateDataTypePtr + EventPrivateDataTypePtr; + typedef EventListener ListenerType; + typedef uintptr_t IdType; + + /** + * Empty (NULL) value of emitter's Id. + */ + static const IdType emptyId; + + public: + ListenerEventEmitter() : m_listener(NULL) + {} + + public: + virtual ~ListenerEventEmitter() + {} + + /** + * Sets event's private data. + * Event's private data object has to implement @see IEventPrivateData + * interface. + * @param data Private data. + * @remarks Practically private dat should be only set at object creation + * and + * not chaged during this object lifetime. + */ + virtual void setEventPrivateData(const EventPrivateDataTypePtr& data) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_privateData = data; + } + + /** + * Gets event's private data. + * @return Private data. + */ + virtual EventPrivateDataTypePtr getEventPrivateData() + { + DPL::Mutex::ScopedLock lock(&m_mtx); + return m_privateData; + } + + /** + * Sets listener. + * Object set as listener has to implement @see EventListener interface. + * @param listener Listener object. + * @remarks Doesn't take ownership over this object. + * It's suggested to use singletons to have one listener for all + * events (no dynamic allocation overhead). + */ + virtual void setListener(ListenerType* listener) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_listener = listener; + } + + /** + * Emits event. + * @param event Event to emit. + */ + virtual void emit(const EventPtrType& event) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + EventPtrType copy(new EventType(*event.Get())); + if (m_listener) { + copy->setPrivateData(m_privateData); + m_listener->postAnswer(copy); + } + } + + /** + * Gets id. + * @return Event's id. + * @remarks Id is implemented as value of `this` pointer. + */ + virtual IdType getId() + { + return reinterpret_cast(this); + } + + protected: + DPL::Mutex m_mtx; ///< Mutex for thread-safety. + ListenerType* m_listener; ///< Event listener object. + EventPrivateDataTypePtr m_privateData; ///< Private data. +}; + +template +const typename ListenerEventEmitter::IdType ListenerEventEmitter< + EventClass>::emptyId = 0; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ diff --git a/src_mobile/Commons/Range.h b/src_mobile/Commons/Range.h new file mode 100644 index 0000000..ab731e1 --- /dev/null +++ b/src_mobile/Commons/Range.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_RANGE_H_ +#define WRTDEVICEAPIS_COMMONS_RANGE_H_ + +namespace WrtDeviceApis { +namespace Commons { +/** + * Stores data describing a range of values. + */ +template +struct Range +{ + /** + * Type of value. + */ + typedef Type ValueType; + + /** + * Value representing minimum. + */ + ValueType min; + + /** + * Value representing maximum. + */ + ValueType max; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_RANGE_H_ diff --git a/src_mobile/Commons/Regex.cpp b/src_mobile/Commons/Regex.cpp new file mode 100644 index 0000000..9284d3f --- /dev/null +++ b/src_mobile/Commons/Regex.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "Regex.h" + +namespace WrtDeviceApis { +namespace Commons { +bool validate(const std::string &pattern, + const std::string &value, + unsigned int options) +{ + pcrecpp::RE_Options pcreOpt; + if (options & VALIDATE_MATCH_CASELESS) { + pcreOpt.set_caseless(true); + } + pcrecpp::RE re(pattern, pcreOpt); + if (options & VALIDATE_MATCH_FULL) { + return re.FullMatch(value); + } + return re.PartialMatch(value); +} + +std::string filter(const std::string &pattern, + const std::string &value) +{ + pcrecpp::RE re(pattern); + std::string ret = static_cast(value); + re.GlobalReplace("", &ret); + return ret; +} + +std::string toUpper(const std::string &value) +{ + pcrecpp::RE re(LOWER_P); + std::string ret = static_cast(value); + re.GlobalReplace(UPPER_P, &ret); + return ret; +} +} +} // WrtDeviceApisCommon diff --git a/src_mobile/Commons/Regex.h b/src_mobile/Commons/Regex.h new file mode 100644 index 0000000..f6c046b --- /dev/null +++ b/src_mobile/Commons/Regex.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_REGEX_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +const unsigned int VALIDATE_MATCH_CASELESS = 0x0001; //use when you want to + // make caseless match +const unsigned int VALIDATE_MATCH_FULL = 0x0002; //use when you want + // supplied text + // matches a supplied + // pattern exactly +const std::string LOWER_P = "p"; +const std::string UPPER_P = "P"; + +/** + * Validates value against pattern + * @param pattern Regexp pattern + * @param value String to validate + * @param options Modifiers for a match. + * @return True when value is matched against pattern + */ +bool validate(const std::string &pattern, + const std::string &value, + unsigned int options = 0); + +/** + * Filter value against pattern(Any character except "0-9+#*Pp" will be removed + * from value) + * @param pattern Regexp pattern + * @param value String to be filtered + * @return filtered value + */ +std::string filter(const std::string &pattern, + const std::string &value); + +/** + * Replace character "p" in value by "P" + * @param value String to be replaced + * @return replaced value + */ +std::string toUpper(const std::string &value); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_H_ diff --git a/src_mobile/Commons/RegexPatterns.h b/src_mobile/Commons/RegexPatterns.h new file mode 100644 index 0000000..3c9ceb6 --- /dev/null +++ b/src_mobile/Commons/RegexPatterns.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +const std::string PATTERN_PHONE_NUMBER_FILTER("[^0-9+#*Pp]"); +const std::string PATTERN_PHONE_NUMBER("^[0-9#+*]+$"); +const std::string PATTERN_PHONE_NUMBER_P("^\\+?[0-9#*Pp]*[0-9][0-9#*Pp]*$"); +const std::string PATTERN_PHONE_NUMBER_PW("^[0-9#+*PpWw]+$"); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ diff --git a/src_mobile/Commons/RegexUtils.cpp b/src_mobile/Commons/RegexUtils.cpp new file mode 100644 index 0000000..db749e7 --- /dev/null +++ b/src_mobile/Commons/RegexUtils.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "RegexUtils.h" +#include +#include "StringUtils.h" + +namespace WrtDeviceApis { +namespace Commons { +std::string addStartPositionMark(const std::string &value) +{ + if (!String::startsWith(value, "^") && !String::startsWith(value, ".*")) { + return "^" + value; + } + return value; +} + +std::string addEndPositionMark(const std::string &value) +{ + if ((!String::endsWith(value, "$") || String::endsWith(value, "\\$")) && + !String::endsWith(value, ".*")) + { + return value + "$"; + } + return value; +} + +std::string addStartAndEndPositionMark(const std::string &value) +{ + return addEndPositionMark(addStartPositionMark(value)); +} + +std::string preparePercent(const std::string& str) +{ + std::string result = escape(str); + pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2\\\\*", &result); + pcrecpp::RE("(([^\\\\])%|^()%)").GlobalReplace("\\2.*", &result); + return result; +} + +std::string prepareAsterisk(const std::string& str) +{ + std::string result = escape(str); + // Replaces single wildcard "*" with version more compliant with Perl + // regular exrepssions, i.e. ".*". + pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2.*", &result); + return result; +} + +std::string escape(const std::string& str) +{ + std::string result = str; + // Escape standard regular expressions' metacharacters, + // i.e.: \, ., -, +, ?, (, ), [, ], ^, $, | + const char* metas = "(\\.|\\-|\\+|\\?|\\(|\\)|\\[|\\]|\\^|\\$|\\|" + "|(\\\\[^\\*\\%]|\\\\$))"; // \*, \% won't get + // additional '\' + pcrecpp::RE(metas).GlobalReplace("\\\\\\1", &result); + return result; +} +} +} // WrtDeviceApisCommon diff --git a/src_mobile/Commons/RegexUtils.h b/src_mobile/Commons/RegexUtils.h new file mode 100644 index 0000000..a06e1cd --- /dev/null +++ b/src_mobile/Commons/RegexUtils.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Adds ^ character at the beginning in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addStartPositionMark(const std::string &value); + +/** + * Adds $ character at the end in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addEndPositionMark(const std::string &value); + +/** + * Adds ^ character at the beginning and $ the end in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addStartAndEndPositionMark(const std::string &value); + +/** + * Converts typical string with wildcard '%' to proper perl-like regular + * expression's pattern. + * @param str String that came from JS. + * @return Proper regular expression's pattern. + * @remarks Calling it twice will (probably?) cause double escaping. + */ +std::string preparePercent(const std::string& str); + +/** + * Converts typical string with wildcard '*' to proper perl-like regular + * expression's pattern. + * @param str String that came from JS. + * @return Proper regular expression's pattern. + * @remarks Calling it twice will (probably?) cause double escaping. + */ +std::string prepareAsterisk(const std::string& str); + +/** + * Escapes regex special characters. + * @param str String to escape. + * @return String with regex special characters escaped. + */ +std::string escape(const std::string& str); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ diff --git a/src_mobile/Commons/StaticAssert.h b/src_mobile/Commons/StaticAssert.h new file mode 100644 index 0000000..bbd19f2 --- /dev/null +++ b/src_mobile/Commons/StaticAssert.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file StaticAssert.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H +#define WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H + +namespace WrtDeviceApis { +namespace Commons { +template +struct CompileTimeChecker +{ + CompileTimeChecker(...); +}; + +template<> +struct CompileTimeChecker {}; + +#define STATIC_CHECK(expr, msg) \ + { \ + class ERROR_##msg {}; \ + CompileTimeChecker<(expr) != 0>((ERROR_##msg())); \ + } + +/** + * Define used to inform about errors in compilation time + * useful in templates + * @param msg - message to be displayed, + * msg have to be a valid C++ identifier, + * other way reported errors will be meaningless + * @param C - instance of object which caused problem + * error generated by compiler display type of C + * */ +#define STATIC_ERROR(msg, C) \ + { \ + C->_##msg(); \ + } +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H diff --git a/src_mobile/Commons/StringBuilder.cpp b/src_mobile/Commons/StringBuilder.cpp new file mode 100644 index 0000000..7fb1cb9 --- /dev/null +++ b/src_mobile/Commons/StringBuilder.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include "Exception.h" +#include "StringBuilder.h" + +namespace WrtDeviceApis { +namespace Commons { +class StringBuilderImpl +{ + public: + StringBuilderImpl() : m_counter(1) + {} + + void append(const std::string& str) + { + if (!(m_ss << str)) { + m_ss.clear(); + ThrowMsg(PlatformException, "Couldn't append string."); + } + } + + void append(const StringBuilderImpl* impl) + { + if (!(m_ss << impl->m_ss)) { + m_ss.clear(); + ThrowMsg(PlatformException, + "Couldn't append string builder."); + } + } + + void addRef() + { + ++m_counter; + } + + void deref() + { + if (0 == --m_counter) { + delete this; + } + } + + StringBuilderImpl* clone() + { + if (1 == m_counter) { + return this; + } + + --m_counter; + + StringBuilderImpl* result = new StringBuilderImpl(); + result->m_ss << m_ss; + return result; + } + + std::string toString() const + { + return m_ss.str(); + } + + private: + std::stringstream m_ss; + unsigned int m_counter; +}; + +StringBuilder::StringBuilder() : m_impl(new StringBuilderImpl()) +{} + +StringBuilder::~StringBuilder() +{ + m_impl->deref(); +} + +StringBuilder::StringBuilder(const StringBuilder& other) +{ + other.m_impl->addRef(); + m_impl = other.m_impl; +} + +StringBuilder & StringBuilder::operator=(const StringBuilder& other) +{ + if (this == &other) { + return *this; + } + + other.m_impl->addRef(); + + m_impl->deref(); + m_impl = other.m_impl; + + return *this; +} + +StringBuilder& StringBuilder::append(const std::string& str) +{ + m_impl = m_impl->clone(); + m_impl->append(str); + return *this; +} + +StringBuilder& StringBuilder::append(const StringBuilder& builder) +{ + m_impl = m_impl->clone(); + m_impl->append(builder.m_impl); + return *this; +} + +std::string StringBuilder::toString() const +{ + return m_impl->toString(); +} +} +} // WrtDeviceApisCommon diff --git a/src_mobile/Commons/StringBuilder.h b/src_mobile/Commons/StringBuilder.h new file mode 100644 index 0000000..fa12c37 --- /dev/null +++ b/src_mobile/Commons/StringBuilder.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ +#define WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +class StringBuilderImpl; + +class StringBuilder +{ + public: + StringBuilder(); + StringBuilder(const StringBuilder& other); + ~StringBuilder(); + + StringBuilder& operator=(const StringBuilder& other); + + StringBuilder& append(const std::string& str); + StringBuilder& append(const StringBuilder& builder); + std::string toString() const; + + private: + StringBuilderImpl* m_impl; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ diff --git a/src_mobile/Commons/StringUtils.cpp b/src_mobile/Commons/StringUtils.cpp new file mode 100644 index 0000000..0b432b6 --- /dev/null +++ b/src_mobile/Commons/StringUtils.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include "StringUtils.h" + +namespace WrtDeviceApis { +namespace Commons { +namespace String { +std::string lTrim(const std::string& str) +{ + std::string result = str; + result.erase(result.begin(), + std::find_if(result.begin(), result.end(), + std::not1(std::ptr_fun(std::isspace)))); + return result; +} + +std::string rTrim(const std::string& str) +{ + std::string result = str; + result.erase(std::find_if(result.rbegin(), result.rend(), + std::not1(std::ptr_fun( + std::isspace))).base(), result.end()); + return result; +} + +std::string trim(const std::string& str) +{ + return lTrim(rTrim(str)); +} + +bool startsWith(const std::string& str, + const std::string& startStr) +{ + return str.find(startStr) == 0; +} + +bool endsWith(const std::string& str, + const std::string& endStr) +{ + std::size_t pos = str.rfind(endStr); + if (pos == std::string::npos) { + return false; + } + return pos == str.length() - endStr.length(); +} + +std::string unique(const std::string& str, + const char needle) +{ + std::string result = str; + + std::string::size_type pos = 0; + while ((pos = result.find_first_of(needle, pos)) < std::string::npos) { + std::string::size_type last = result.find_first_not_of(needle, pos); + if (last == std::string::npos) { + last = result.size(); + } + if (last - pos > 1) { + result.erase(pos + 1, last - pos - 1); + } + pos = last; + } + + return result; +} + +bool inCStringArray(const std::string& needle, + const char* stack[]) +{ + while (*stack) { + if (needle == *stack) { + return true; + } + ++stack; + } + return false; +} + +char* strdup(const char* str) +{ + char* result = ::strdup(str); + if (NULL == result) { + throw std::bad_alloc(); + } + return result; +} + +std::string merge(const std::vector& strs, + std::string::value_type delim) +{ + typedef std::vector Strings; + + std::ostringstream ss; + if (!strs.empty()) { + for (Strings::size_type i = 0; i < strs.size() - 1; ++i) { + ss << strs[i] << delim; + } + ss << strs.at(strs.size() - 1); + } + return ss.str(); +} + +std::vector split(const std::string& str, + std::string::value_type delim) +{ + std::vector result; + std::string::size_type begin = 0, end = 0; + while ((end = str.find_first_of(delim, begin))) { + std::string part = (std::string::npos == end ? + str.substr(begin) : + str.substr(begin, end - begin)); + if (!part.empty()) { + result.push_back(part); + } + if (std::string::npos == end) { + break; + } + begin = end + 1; + } + return result; +} + +int toInt(const std::string& str) +{ + return convertTo(str); +} +} +} +} diff --git a/src_mobile/Commons/StringUtils.h b/src_mobile/Commons/StringUtils.h new file mode 100644 index 0000000..b36071f --- /dev/null +++ b/src_mobile/Commons/StringUtils.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file StringUtils.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STRINGUTILS_H_ +#define WRTDEVICEAPIS_COMMONS_STRINGUTILS_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +namespace String { +/** + * Removes spaces from begining of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string lTrim(const std::string& str); + +/** + * Removes spaces from end of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string rTrim(const std::string& str); + +/** + * Removes spaces from begining and end of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string trim(const std::string& str); + +/** + * Checks if str starts with startStr + * @param str String to be searched. + * @param startStr String to be found at the beginning of str. + * @return true when str starts with startStr, false otherwise. + */ +bool startsWith(const std::string& str, const std::string& startStr); + +/** + * Checks if str ends with startStr + * @param str String to be searched. + * @param endStr String to be found at the end of str. + * @return true when str starts with startStr, false otherwise. + */ +bool endsWith(const std::string& str, const std::string& endStr); + +/** + * Merges consecutive groups of duplicate characters into one. + * @param str String to remove characters from. + * @param needle Character for which groups of duplicates to merge. + * @return String with group of duplicate characters merged. + * @code + * ... + * std::string str = "Aala maa kota"; + * std::string uniq = unique(str, 'a'); + * uniq == "Ala ma kota"; + * ... + * @endcode + */ +std::string unique(const std::string& str, const char needle); + +/** + * Checks if supplied string exists in specified array of c-strings. + * @param needle String to verify. + * @param stack Array of c-strings which last element should be NULL. + * @return True if string exists in array, false otherwise. + * @remarks Last element of array should be NULL, otherwise there is no + * way to calculate its number of elements. + */ +bool inCStringArray(const std::string& needle, const char* stack[]); + +/** + * Duplicates a string. + * @param str String to duplicate. + * @return String copy. + * @throw std::bad_alloc If allocation fails. + * @remarks Ownership passed to the caller. String has to be deallocated using + * free() function. + */ +char* strdup(const char* str); +inline char* strdup(const std::string& str) +{ + return strdup(str.c_str()); +} + +std::string merge(const std::vector& strs, + std::string::value_type delim); + +std::vector split(const std::string& str, + std::string::value_type delim); + +/** + * @deprecated Use convertTo(). + */ +int toInt(const std::string& str) WRT_PLUGINS_DEPRECATED; + +/** + * Converts string to specified type. + * + * @tparam T Type to convert to. + * @param str String to convert. + * @return Converted value. + * @throw ConversionException If conversion fails. + * + * @remarks T must implement default constructor and an implementation + * of input string operator for T must exist. + */ +template +T convertTo(const std::string& str) +{ + T result; + std::istringstream iss(str); + if (!(iss >> result)) { + Throw(ConversionException); + } + return std::move(result); +} + +/** + * Converts a given value to string. + * + * @tparam T Type of the value to convert. It is deduced by the compiler. + * @param data Value to convert. + * @return Value converted to string. + * @throw ConversionException If operation fails. + * + * @remarks Output stream operator for type T must exist. + */ +template +std::string parse(const T& data) +{ + std::ostringstream oss; + if (!(oss << data)) { + Throw(ConversionException); + } + return oss.str(); +} +} +} +} + +#endif diff --git a/src_mobile/Commons/ThreadPool.cpp b/src_mobile/Commons/ThreadPool.cpp new file mode 100644 index 0000000..fd5cd3a --- /dev/null +++ b/src_mobile/Commons/ThreadPool.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * ControllersFactory.cpp + * + * Created on: 2010-06-28 + * Author: kmajewski + */ + +#include + +#include +#include + +#include "ThreadPool.h" +#include "Exception.h" + +namespace WrtDeviceApis { +namespace Commons { +ThreadPool &ThreadPool::getInstance() +{ + static ThreadPool theInstance; + return theInstance; +} + +DPL::Event::AbstractEventDispatcher *ThreadPool::getDispatcher( + DPL::Event::ThreadEventDispatcher &callingThreadDispatcher) +{ + DPL::Thread *currentThread = DPL::Thread::GetCurrentThread(); + //if we are in main thread + if (NULL == currentThread) { + return &DPL::Event::GetMainEventDispatcherInstance(); + } + callingThreadDispatcher.SetThread(currentThread); + return &callingThreadDispatcher; +} + +ThreadPool::ThreadPool() +{} + +ThreadPool::~ThreadPool() +{ + for (ThreadHandleMap::const_iterator it = m_threadHandlers.begin(); it + != m_threadHandlers.end(); ++it) + { + delete (*it).second; + } +} + +DPL::Thread* ThreadPool::getThreadHandleCreateIfNotExists( + ThreadEnum::Enumeration type) +{ + DPL::Mutex::ScopedLock lock(&m_threadHandlersMutex); + ThreadHandleMap::iterator element = m_threadHandlers.find(type); + + //if element does not exists in the map + if (m_threadHandlers.end() == element) { + DPL::Thread* newThread = new DPL::Thread(); + m_threadHandlers.insert( + m_threadHandlers.begin(), + std::pair(type, newThread)); + newThread->Run(); + return newThread; + } + return (*element).second; +} + +DPL::Thread *ThreadPool::getThreadRef(ThreadEnum::Enumeration type) +{ + DPL::Thread *thandle = NULL; + if (type < 0 || type >= ThreadEnum::size) { + Throw(InvalidArgumentException); + } + /* we could stay with + * getThreadHandleCreateIfNotExists(type); + * but by switch we can attach actually one thread to more than one + * ThreadEnums + */ + switch (type) { + case ThreadEnum::NULL_THREAD: + thandle = NULL; + break; + case ThreadEnum::CAMERA_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CAMERA_THREAD); + break; + case ThreadEnum::CALENDAR_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CALENDAR_THREAD); + break; + case ThreadEnum::TELEPHONY_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::TELEPHONY_THREAD); + break; + case ThreadEnum::APPLAUNCHER_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::APPLAUNCHER_THREAD); + break; + case ThreadEnum::APPCONFIG_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::APPCONFIG_THREAD); + break; + case ThreadEnum::MESSAGING_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::FILESYSTEM_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::FILESYSTEM_THREAD); + break; + case ThreadEnum::GALLERY_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::GALLERY_THREAD); + break; + case ThreadEnum::CONTACT_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CONTACT_THREAD); + break; + case ThreadEnum::BONDI_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::BONDI_THREAD); + break; + case ThreadEnum::GEOLOCATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::GEOLOCATION_THREAD); + break; + case ThreadEnum::DEVICESTATUS_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::DEVICESTATUS_THREAD); + break; + case ThreadEnum::PROFILE_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::HAPTICS_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::ACCELEROMETER_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::ACCELEROMETER_THREAD); + break; + case ThreadEnum::ORIENTATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::ORIENTATION_THREAD); + break; + case ThreadEnum::TASK_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::TASK_THREAD); + break; + case ThreadEnum::POWER_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::POWER_THREAD); + break; + case ThreadEnum::PLUGIN_TEMPLETE_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::PLUGIN_TEMPLETE_THREAD); + break; + case ThreadEnum::BLUETOOTH_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::BLUETOOTH_THREAD); + break; + case ThreadEnum::APPLICATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::APPLICATION_THREAD); + break; + case ThreadEnum::GYROSCOPE_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::GYROSCOPE_THREAD); + break; + case ThreadEnum::CLOCK_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CLOCK_THREAD); + break; + case ThreadEnum::SYSTEMINFO_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::SYSTEMINFO_THREAD); + break; + case ThreadEnum::CALLHISTORY_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::CALLHISTORY_THREAD); + break; + case ThreadEnum::ACCOUNT_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::CALLHISTORY_THREAD); + break; + case ThreadEnum::NFC_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::NFC_THREAD); + break; + case ThreadEnum::MEDIACONTENT_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::MEDIACONTENT_THREAD); + break; + case ThreadEnum::SE_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::SE_THREAD); + break; + case ThreadEnum::DOWNLOAD_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::DOWNLOAD_THREAD); + break; + case ThreadEnum::PUSH_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::PUSH_THREAD); + break; + case ThreadEnum::SYNC_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::SYNC_THREAD); + break; + // ..... + default: + LogError("no case statement for ThreadEnum"); + Throw(InvalidArgumentException); + } + return thandle; +} +} +} // WrtDeviceApisCommon diff --git a/src_mobile/Commons/ThreadPool.h b/src_mobile/Commons/ThreadPool.h new file mode 100644 index 0000000..ada3233 --- /dev/null +++ b/src_mobile/Commons/ThreadPool.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * ControllersFactory.h + * + * Created on: 2010-06-28 + * Author: kmajewski + */ + +#ifndef WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ +#define WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class ThreadEnum +{ + private: + ThreadEnum() + {} + + public: + enum Enumeration + { + NULL_THREAD = 0, + CAMERA_THREAD, + CALENDAR_THREAD, + TELEPHONY_THREAD, + APPLAUNCHER_THREAD, + MESSAGING_THREAD, + FILESYSTEM_THREAD, + UI_THREAD, + APPCONFIG_THREAD, + GALLERY_THREAD, + CONTACT_THREAD, + BONDI_THREAD, + GEOLOCATION_THREAD, + DEVICESTATUS_THREAD, + PROFILE_THREAD, + HAPTICS_THREAD, + ACCELEROMETER_THREAD, + ORIENTATION_THREAD, + TASK_THREAD, + POWER_THREAD, + PLUGIN_TEMPLETE_THREAD, + BLUETOOTH_THREAD, + APPLICATION_THREAD, + GYROSCOPE_THREAD, + CLOCK_THREAD, + SYSTEMINFO_THREAD, + CALLHISTORY_THREAD, + ACCOUNT_THREAD, + NFC_THREAD, + MEDIACONTENT_THREAD, + SE_THREAD, + DOWNLOAD_THREAD, + PUSH_THREAD, + SYNC_THREAD, + //.... + size + }; +}; + +class ThreadPool : private DPL::Noncopyable +{ + private: + typedef std::map ThreadHandleMap; + ThreadHandleMap m_threadHandlers; + DPL::Mutex m_threadHandlersMutex; + + DPL::Thread *getThreadHandleCreateIfNotExists(ThreadEnum::Enumeration type); + + //DPL::MainEventDispatcher m_mainEventDispatcher; + + ThreadPool(); + + public: + ~ThreadPool(); + + /* + * @throws: WrtDeviceApis::Commons::InvalidArgumentException + */ + DPL::Thread * getThreadRef(ThreadEnum::Enumeration type); + + /* + * Get proper dispatcher for current calling thread + */ + DPL::Event::AbstractEventDispatcher *getDispatcher( + DPL::Event::ThreadEventDispatcher &callingThreadDispatcher); + + static ThreadPool& getInstance(); +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ diff --git a/src_mobile/Commons/TimeUtils.cpp b/src_mobile/Commons/TimeUtils.cpp new file mode 100644 index 0000000..ce5cce8 --- /dev/null +++ b/src_mobile/Commons/TimeUtils.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TimeUtils.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + */ + +#include "TimeUtils.h" +#include + +namespace WrtDeviceApis { +namespace Commons { +namespace Time { +struct tm* localtime_r(long long int* timep, struct tm* result) +{ + UErrorCode status = U_ZERO_ERROR; + UCalendar *cal; + + if (!result || !timep) { + return NULL; + } + + cal = ucal_open(NULL, 0, NULL, UCAL_DEFAULT, &status); + + if (U_FAILURE(status)) { + return NULL; + } + + ucal_setMillis(cal, (*timep * (double)1000.0), &status); + + result->tm_sec = ucal_get(cal, UCAL_SECOND, &status); + result->tm_min = ucal_get(cal, UCAL_MINUTE, &status); + result->tm_hour = ucal_get(cal, UCAL_HOUR, &status); + result->tm_mday = ucal_get(cal, UCAL_DAY_OF_MONTH, &status); + result->tm_mon = ucal_get(cal, UCAL_MONTH, &status); + result->tm_year = ucal_get(cal, UCAL_YEAR, &status); + result->tm_wday = ucal_get(cal, UCAL_DAY_OF_WEEK, &status); + result->tm_yday = ucal_get(cal, UCAL_DAY_OF_YEAR, &status); + result->tm_isdst = ucal_get(cal, UCAL_DST_OFFSET, &status); + + ucal_close(cal); + + if (U_FAILURE(status)) { + return NULL; + } else { + return result; + } +} +} +} +} diff --git a/src_mobile/Commons/TimeUtils.h b/src_mobile/Commons/TimeUtils.h new file mode 100644 index 0000000..de55e4c --- /dev/null +++ b/src_mobile/Commons/TimeUtils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TimeUtils.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_TIMEUTILS_H_ +#define WRTDEVICEAPIS_COMMONS_TIMEUTILS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +namespace Time { +struct tm* localtime_r(long long int* timep, struct tm* result); +} +} +} +#endif diff --git a/src_mobile/Commons/TypeTraits.h b/src_mobile/Commons/TypeTraits.h new file mode 100644 index 0000000..bcc98f7 --- /dev/null +++ b/src_mobile/Commons/TypeTraits.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ +#define WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +template +struct IsNull +{ + static bool value(const T&) + { + return false; + } +}; + +template +struct IsNull +{ + static bool value(T* ptr) + { + return ptr == NULL; + } +}; + +template +struct IsNull > +{ + static bool value(const DPL::SharedPtr& ptr) + { + return ptr.Get() == NULL; + } +}; + +template +struct AlwaysFalse +{ + static const bool value = false; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ diff --git a/src_mobile/Commons/TypesDeclaration.h b/src_mobile/Commons/TypesDeclaration.h new file mode 100644 index 0000000..0f2dca2 --- /dev/null +++ b/src_mobile/Commons/TypesDeclaration.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_TYPES_DECLARATION_ +#define WRTDEVICEAPIS_COMMONS_TYPES_DECLARATION_ + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +struct AceFeature +{ + AceFeature(const std::string& featName) : name(featName) {} + std::string name; +}; + +typedef std::vector AceFeatures; + +struct AceDeviceCapParam +{ + AceDeviceCapParam(const std::string& parName, + const std::string& parVal) : name(parName), + value(parVal) + {} + + std::string name; + std::string value; +}; + +typedef std::vector AceDeviceCapParams; + +struct AceDeviceCapability +{ + AceDeviceCapability() {} + AceDeviceCapability(const std::string& name, + const AceDeviceCapParams& params) : + devCapName(name), + devCapParams(params) + {} + + std::string devCapName; + AceDeviceCapParams devCapParams; +}; + +typedef std::vector AceDeviceCaps; + +struct AceFunction +{ + std::string name; + AceFeatures features; + AceDeviceCaps deviceCapabilities; +}; +} // namespace Commons +} // namespace WrtDeviceApis + +#endif diff --git a/src_mobile/Commons/WrtAccess/WrtAccess.cpp b/src_mobile/Commons/WrtAccess/WrtAccess.cpp new file mode 100644 index 0000000..766ca44 --- /dev/null +++ b/src_mobile/Commons/WrtAccess/WrtAccess.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "WrtAccess.h" +#include +#include + +#include "popup-runner.h" +IMPLEMENT_SAFE_SINGLETON(WrtDeviceApis::Commons::WrtAccess) + +namespace { +/** + * Helper class - single parameter and its value + */ +struct AceParam +{ + const char *name; + const char *value; + + AceParam() : + name(NULL), value(NULL) + {} + + AceParam(const char *name, const char *value) : + name(name), value(value) + {} +}; + +/** + * Helper class - list of params for single dev cap + */ +struct AceParamList +{ + size_t count; + AceParam* param; + AceParamList() : + count(0), + param(NULL) + {} +}; + +struct DeviceCapParamPolicy +{ + typedef AceParamList* Type; + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + if (ptr) { + delete[] ptr->param; + } + delete[] ptr; + } +}; + +/** + * Helper class - modified ScopedArray for ace_param_list_t + */ +class ScopedDeviceCapArray : public DPL::ScopedResource +{ + public: + explicit ScopedDeviceCapArray(AceParamList *ptr = + DeviceCapParamPolicy::NullValue()) : + DPL::ScopedResource(ptr) + {} + + AceParamList & operator [](std::ptrdiff_t k) const + { + Assert(this->m_value != DeviceCapParamPolicy::NullValue() && + "Dereference of scoped NULL array!"); + Assert(k >= 0 && "Negative array index"); + + return this->m_value[k]; + } +}; +} // namespace + +namespace WrtDeviceApis { +namespace Commons { +WrtAccess::WrtAccess() : + m_sessionId(GenerateSessionId()), + m_pluginOwners(0) +{} + +WrtAccess::~WrtAccess() +{} + +WrtAccess::SessionId WrtAccess::GenerateSessionId() +{ + const size_t SESSION_ID_LENGTH = 32; + + std::ostringstream pid; + pid << static_cast(getpid()); + + std::string session_id = pid.str(); + + session_id.reserve(session_id.length() + SESSION_ID_LENGTH); + + for (size_t i = 0; i < SESSION_ID_LENGTH; ++i) { + int c = random() % 16; + + session_id += (c < 10 ? + static_cast('0' + c) : + static_cast('A' + c - 10)); + } + return session_id; +} + +void WrtAccess::initialize(int widgetId) +{ + _D("initialize"); + if (widgetId < 0) { + _E("Invalid widget id"); + Throw(Exception); + } + + m_widgetId = widgetId; + + if (!m_pluginOwners++) { + DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON"); + ace_return_t ret = ace_client_initialize(Wrt::Popup::run_popup); + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + Assert(ACE_OK == ret); + } +} + +void WrtAccess::deinitialize(int /*widgetId*/) +{ + _D("deinitialize"); + + if (!--m_pluginOwners) { + DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON"); + ace_return_t ret = ace_client_shutdown(); + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + Assert(ACE_OK == ret); + } +} + +int WrtAccess::getWidgetId() const +{ + return m_widgetId; +} + +WrtAccess::CheckAccessReturnType WrtAccess::checkAccessControl(const AceFunction& aceFunction) const +{ + Assert( + m_pluginOwners && "WrtAccessSingleton needs to be initialized with" + "WidgetId during on_widget_start_callback in each plugin"); + size_t deviceCount = aceFunction.deviceCapabilities.size(); + + DPL::ScopedArray deviceScopedArray; + ScopedDeviceCapArray paramsScopedArray; + + if (deviceCount) { + deviceScopedArray.Reset(new const char*[deviceCount]); + paramsScopedArray.Reset(new AceParamList[deviceCount]); + + for (size_t i = 0; i < deviceCount; ++i) { + deviceScopedArray[i] = + aceFunction.deviceCapabilities.at(i).devCapName.c_str(); + paramsScopedArray[i].count = + aceFunction.deviceCapabilities.at(i).devCapParams.size(); + + paramsScopedArray[i].param = + new AceParam[paramsScopedArray[i].count]; + + for (size_t j = 0; j < paramsScopedArray[i].count; ++j) { + paramsScopedArray[i].param[j].name = + aceFunction.deviceCapabilities.at(i). + devCapParams[j].name.c_str(); + paramsScopedArray[i].param[j].value = + aceFunction.deviceCapabilities.at(i). + devCapParams[j].value.c_str(); + } + } + } + + size_t featuresCount = aceFunction.features.size(); + + DPL::ScopedArray featureScopedArray; + if (featuresCount) { + featureScopedArray.Reset(new const char*[featuresCount]); + + for (size_t i = 0; i < featuresCount; ++i) { + featureScopedArray[i] = + aceFunction.features.at(i).name.c_str(); + } + } + + _D("constructing ACE request"); + + ace_request_t aceRequest; + aceRequest.session_id = + const_cast(m_sessionId.c_str()); + aceRequest.widget_handle = getWidgetId(); + aceRequest.feature_list.count = featuresCount; + aceRequest.feature_list.items = + const_cast(featureScopedArray.Get()); + aceRequest.dev_cap_list.count = deviceCount; + aceRequest.dev_cap_list.items = new ace_dev_cap_t[deviceCount]; + + const char** devCapNames = deviceScopedArray.Get(); + AceParamList* paramList = paramsScopedArray.Get(); + + unsigned int i; + for (i = 0; i < deviceCount; ++i) { + aceRequest.dev_cap_list.items[i].name = + const_cast(devCapNames[i]); + aceRequest.dev_cap_list.items[i].param_list.count = paramList[i].count; + aceRequest.dev_cap_list.items[i].param_list.items = + new ace_param_t[paramList[i].count]; + unsigned int j; + for (j = 0; j < paramList[i].count; ++j) { + aceRequest.dev_cap_list.items[i].param_list.items[j].name = + const_cast(paramList[i].param[j].name); + aceRequest.dev_cap_list.items[i].param_list.items[j].value = + const_cast(paramList[i].param[j].value); + } + } + + ace_check_result_t aceCheckResult = ACE_PRIVILEGE_DENIED; + DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON"); + ace_return_t ret = ace_check_access_ex(&aceRequest, &aceCheckResult); + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + for (i = 0; i < deviceCount; ++i) { + delete[] aceRequest.dev_cap_list.items[i].param_list.items; + } + delete[] aceRequest.dev_cap_list.items; + + if (ACE_OK != ret) { + _E("Error in ace check: %d", static_cast(ret)); + return CHECK_ACCESS_INTERNAL_ERROR; + } + + if (aceCheckResult == ACE_ACCESS_GRANTED) { + return CHECK_ACCESS_GRANTED; + } + else if (aceCheckResult == ACE_PRIVILEGE_DENIED) { + return CHECK_ACCESS_PRIVILEGE_DENIED; + } + else if (aceCheckResult == ACE_PRIVACY_DENIED) { + return CHECK_ACCESS_PRIVACY_DENIED; + } + + return CHECK_ACCESS_INTERNAL_ERROR; +} +} +} // WrtDeviceApisCommon diff --git a/src_mobile/Commons/WrtAccess/WrtAccess.h b/src_mobile/Commons/WrtAccess/WrtAccess.h new file mode 100644 index 0000000..18893a0 --- /dev/null +++ b/src_mobile/Commons/WrtAccess/WrtAccess.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ACCESS_H_ +#define WRT_PLUGINS_WRT_ACCESS_H_ + +#include + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class WrtAccess +{ + public: + enum CheckAccessReturnType + { + CHECK_ACCESS_GRANTED, + CHECK_ACCESS_PRIVILEGE_DENIED, + CHECK_ACCESS_PRIVACY_DENIED, + CHECK_ACCESS_INTERNAL_ERROR + }; + + void initialize(int widgetId); + void deinitialize(int widgetId); + int getWidgetId() const; + CheckAccessReturnType checkAccessControl(const AceFunction &aceFunction) const; + + private: + + typedef std::string SessionId; + SessionId GenerateSessionId(); + + WrtAccess(); + virtual ~WrtAccess(); + + int m_widgetId; + SessionId m_sessionId; + size_t m_pluginOwners; + + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton WrtAccessSingleton; +} +} // WrtDeviceApisCommon + +#endif //WRT_PLUGINS_WRT_ACCESS_H_ diff --git a/src_mobile/Commons/WrtAccess/config.cmake b/src_mobile/Commons/WrtAccess/config.cmake new file mode 100644 index 0000000..a31ce63 --- /dev/null +++ b/src_mobile/Commons/WrtAccess/config.cmake @@ -0,0 +1,5 @@ +get_current_path() + +set(SRCS_WRT_ACCESS + ${CURRENT_PATH}/WrtAccess.cpp +) diff --git a/src_mobile/Commons/plugin_initializer_def.h b/src_mobile/Commons/plugin_initializer_def.h new file mode 100644 index 0000000..73a6185 --- /dev/null +++ b/src_mobile/Commons/plugin_initializer_def.h @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief This is a file that you provides interface for wrt-engine while + * loading and using plugin + * If you are a plugin developer you need to plugin_initializer.cpp + * in your module and provide implementation for macros below + */ + +#ifndef WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ +#define WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ + +#include + +typedef java_script_context_t JavaScriptContext; + +#define EXPORT_SYMBOL __attribute__((__visibility__("default"))) + +//DEFINES FOR GLOBAL OBJECTS AVAILABLE IN JAVASCRIPT +/** + * each object which declare this object as parent + * will ba available as global object in javascript + */ +#define WRT_JS_EXTENSION_OBJECT_GLOBAL "GLOBAL_OBJECT" + +/** + * global object bondi + * */ +#define WRT_JS_EXTENSION_OBJECT_BONDI "bondi" + +/** + * global object Widget + * */ +#define WRT_JS_EXTENSION_OBJECT_WIDGET "Widget" + +/** + * global object deviceapis + * */ +#define WRT_JS_EXTENSION_OBJECT_DEVICEAPIS "deviceapis" + +/** + * global object tizen + * */ +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +//HAVE TO BE IMPLEMENTED IN EVERY PLUGIN +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while loading each widget (for every + * loaded widget this function will be called) + * Example: + * plugin_initializer.cpp + * void on_widget_start_callback(int widgetId, JSContextRef context, + * const engine_interface_t *interface) + * { + * //... + * } + * PLUGIN_ON_WIDGET_START(on_widget_start_callback) + */ +#define PLUGIN_ON_WIDGET_START(CALLBACK_NAME) extern "C" const \ + on_widget_start_proc PLUGIN_WIDGET_START_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while loading each widget + * (for every loaded widget this function will be called) + * Example: + * plugin_initializer.cpp + * void on_widget_init_callback(feature_mapping_interface_t *mapping) + * { + * //... + * } + * PLUGIN_ON_WIDGET_INIT(on_widget_init_callback) + */ +#define PLUGIN_ON_WIDGET_INIT(CALLBACK_NAME) extern "C" \ + const on_widget_init_proc PLUGIN_WIDGET_INIT_PROC EXPORT_SYMBOL = \ + CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while unloading each widget (for + * every unloaded widget this function will be called) + * Example: + * void on_widget_stop_callback(int widgetId) + * { + * //... + * } + * PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + */ +#define PLUGIN_ON_WIDGET_STOP(CALLBACK_NAME) extern "C" const \ + on_widget_stop_proc PLUGIN_WIDGET_STOP_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while unloading each page (for every + * loaded page, including nested page, this function will be called) + * Example: + * void on_frame_load_callback(java_script_context_t context) + * { + * //... + * } + * PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) + */ +#define PLUGIN_ON_FRAME_LOAD(CALLBACK_NAME) extern "C" const on_frame_load_proc \ + PLUGIN_FRAME_LOAD_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while ununloading each page (for + * every unloaded page, including nested page, this function will be called) + * Example: + * void on_frame_unload_callback(java_script_context_t context) + * { + * //... + * } + * PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + */ +#define PLUGIN_ON_FRAME_UNLOAD(CALLBACK_NAME) extern "C" const \ + on_frame_unload_proc PLUGIN_FRAME_UNLOAD_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) define an array of structures in your + * plugin_initializer.cpp(!) file describing a JS class (class_definition) and + * it's parent class name (parent_name). + * JS class will be bind to a parent class name (parent_name.jsclass_name). + * Example: + * plugin_initializer.cpp + * PLUGIN_CLASS_MAP_BEGIN + * PLUGIN_CLASS_MAP_ADD_CLASS( + * "bondi", + * WrtPluginBondi::JSICameraManager::getClassInfo()) + * PLUGIN_CLASS_MAP_ADD_CLASS( + * "bondi", + * WrtPluginBondi::JSICameraAnotherClass::getClassInfo()) + * PLUGIN_CLASS_MAP_END + * + */ +#define PLUGIN_CLASS_MAP_BEGIN extern "C" const js_entity_definition_t \ + PLUGIN_CLASS_MAP[] EXPORT_SYMBOL = { + +#define PLUGIN_CLASS_MAP_ADD_INTERFACE(PARENTNAME, \ + INTERFACENAME, \ + JSPRODUCTCLASSTEMPLATE, \ + PRODUCTCONSTRUCTORCB, \ + PRIVDATA) \ + { PARENTNAME, INTERFACENAME, "", JSPRODUCTCLASSTEMPLATE, \ + PRODUCTCONSTRUCTORCB, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_ADD_INTERFACE_PRODUCT(PARENTNAME, OBJECTNAME, \ + INTERFACENAME, PRIVDATA) \ + { PARENTNAME, OBJECTNAME, INTERFACENAME, NULL, NULL, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_ADD_CLASS(PARENTNAME, CLASSNAME, JSCLASSTEMPLATE, \ + PRIVDATA) \ + { PARENTNAME, CLASSNAME, "", JSCLASSTEMPLATE, NULL, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_END { NULL, NULL, NULL, NULL, NULL, NULL } }; + +#define PLUGIN_CLASS_MAP_BEGIN_STATIC static const js_entity_definition_t \ + PLUGIN_CLASS_MAP[] = { + +#define PLUGIN_GET_CLASS_MAP(CALLBACK_NAME) extern "C" const \ + get_widget_entity_map_proc \ + PLUGIN_GET_CLASS_PROC_MAP EXPORT_SYMBOL = CALLBACK_NAME; + +#endif // WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ diff --git a/src_mobile/CommonsJavaScript/CMakeLists.txt b/src_mobile/CommonsJavaScript/CMakeLists.txt new file mode 100755 index 0000000..ecd0317 --- /dev/null +++ b/src_mobile/CommonsJavaScript/CMakeLists.txt @@ -0,0 +1,84 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_JS}) +endmacro() + + +pkg_search_module(webkit2 REQUIRED ewebkit2) + +set(TARGET_NAME ${TARGET_COMMONS_JAVASCRIPT}) + +include_directories(${DIR_JS_COMMONS} + ${wrt-plugin-api_INCLUDE_DIRS} + ${webkit2_INCLUDE_DIRS}} + ) + + +set(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/Converter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ScopedJSStringRef.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSCallbackManager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ScopedJSStringRef.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Validator.cpp + # wrapper for simple version of aceCheckAcces + ${CMAKE_CURRENT_SOURCE_DIR}/Security/SecurityFunctionDeclaration.cpp + #ECMA Script Exception + ${CMAKE_CURRENT_SOURCE_DIR}/JSDOMException.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/DOMExceptionData.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSDOMExceptionFactory.cpp + #Pending Operation support + ${CMAKE_CURRENT_SOURCE_DIR}/JSPendingOperation.cpp +) + + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${webkit2_LIBRARIES} + ${TARGET_COMMONS} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}) + +#utils +install_header_file(PrivateObject.h) +#tools +install_header_file(Converter.h) +install_header_file(Validator.h) +install_header_file(JSUtils.h) +install_header_file(ScopedJSStringRef.h) +#callback manager +install_header_file(JSCallbackManager.h) +#exceptions +install_header_file(JSDOMException.h) +install_header_file(JSDOMExceptionFactory.h) +install_header_file(DOMExceptionData.h) +install_header_file(SecurityExceptions.h) +#static declarations +install_header_file(Security/StaticDeclaration.h) +install_header_file(Security/SecurityFunctionDeclaration.h) +#pending operation +install_header_file(SupportPendingOperation.h) +install_header_file(Utils.h) +install_header_file(JSPendingOperation.h) +install_header_file(JSPendingOperationPrivateObject.h) + diff --git a/src_mobile/CommonsJavaScript/Converter.cpp b/src_mobile/CommonsJavaScript/Converter.cpp new file mode 100644 index 0000000..cdaed58 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Converter.cpp @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include "ScopedJSStringRef.h" +#include "Converter.h" +#include + +using namespace WrtDeviceApis::Commons; + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +Converter::Converter(JSContextRef context) : m_context(context) +{} + +Converter::~Converter() +{} + +JSObjectRef Converter::toJSObjectRef(const JSValueRef& arg) +{ + if (!arg) { + Throw(NullPointerException); + } + JSValueRef exception = NULL; + JSObjectRef result = JSValueToObject(m_context, arg, &exception); + if ((NULL == result) || (NULL != exception)) { + ThrowMsg(ConversionException, "Couldn't convert to a JS Object."); + } + return result; +} + +bool Converter::toBool(const JSValueRef& arg) +{ + return JSValueToBoolean(m_context, arg); +} + +unsigned char Converter::toUChar(const JSValueRef& arg) +{ + return static_cast(toChar(arg)); +} + +char Converter::toChar(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +int Converter::toInt(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +int Converter::toInt(const std::string &arg) +{ + return static_cast(toNumber_(arg)); +} + +long Converter::toLong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +long long Converter::toLongLong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +unsigned long Converter::toULong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +std::size_t Converter::toSizeT(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +std::size_t Converter::toSizeT(const JSStringRef& arg) +{ + return static_cast(toNumber_(arg)); +} + +double Converter::toDouble(const JSValueRef& arg) +{ + return toNumber_(arg); +} + +std::string Converter::toString(int arg) +{ + return toString_(arg); +} + +std::string Converter::toString(unsigned long arg) +{ + return toString_(arg); +} + +std::string Converter::toString(long arg) +{ + return toString_(arg); +} + +std::string Converter::toString(std::size_t arg) +{ + return toString_(arg); +} + +std::string Converter::toString(const JSValueRef& arg) +{ + return toString_(arg); +} + +std::string Converter::tryString(const JSValueRef& arg) +{ + if (!JSValueIsString(m_context, arg) && + !JSValueIsNumber(m_context, arg) && + !JSValueIsBoolean(m_context, arg)) + { + ThrowMsg(ConversionException, + "Argument is not convertable to JS String."); + } + + return toString_(arg); +} + +std::string Converter::toDateString(const JSValueRef& arg) +{ + if (!JSValueIsObject(m_context, arg)) { + ThrowMsg(ConversionException, "Argument is not JS Date."); + } + + return toString_(arg); +} + +std::string Converter::toString(const JSStringRef& arg) +{ + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(arg); + if (jsSize > 0) { + jsSize = jsSize + 1; + DPL::ScopedArray buffer(new char[jsSize]); + size_t written = JSStringGetUTF8CString(arg, buffer.Get(), jsSize); + if (written > jsSize) { + ThrowMsg(ConversionException, + "Conversion could not be fully performed."); + } + result = buffer.Get(); + } + + return result; +} + +time_t Converter::toDateTimeT(const JSValueRef& arg) +{ + struct tm tm = toDateTm(arg); + return mktime(&tm); +} + +tm Converter::toDateTm(const JSValueRef& arg) +{ + std::string stringDate = toDateString(arg); + struct tm result; + char* currentLocale = setlocale(LC_TIME, NULL); + if (currentLocale == NULL) { + ThrowMsg(ConversionException, "Couldn't get current locale."); + } + DPL::ScopedFree currentLocaleCopy(strdup(currentLocale)); + if (setlocale(LC_TIME, "C") == NULL) { + ThrowMsg(ConversionException, "Couldn't set POSIX locale."); + } + if (strptime(stringDate.c_str(), "%a %b %d %Y %T", &result) == NULL) { + ThrowMsg(ConversionException, "Couldn't convert supplied date."); + } + if (setlocale(LC_TIME, currentLocaleCopy.Get()) == NULL) { + ThrowMsg(ConversionException, "Couldn't set previous locale back."); + } + //strptime function doesn't affect tm_isdst flag. + //It may cause -1hr conversion error. Setting it to -1 informs that + //there is no information about daylight saving time. + result.tm_isdst = -1; + return result; +} + +std::vector Converter::toVectorOfUChars(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toUChar); +} + +std::vector Converter::toVectorOfChars(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toChar); +} + +std::vector Converter::toVectorOfInts(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toInt); +} + +std::vector Converter::toVectorOfStrings(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toString); +} + +std::vector Converter::toVectorOfTimeT(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toDateTimeT); +} + +JSValueRef Converter::toJSValueRef(bool arg) +{ + return JSValueMakeBoolean(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(unsigned int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(unsigned long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRefLong(const long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(long long int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(double arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(const std::string& arg) +{ + JSValueRef result = NULL; + JSStringRef jsString = JSStringCreateWithUTF8CString(arg.c_str()); + result = JSValueMakeString(m_context, jsString); + JSStringRelease(jsString); + return result; +} + +JSValueRef Converter::toJSValueRef(const tm& arg) +{ + JSValueRef args[6]; + args[0] = JSValueMakeNumber(m_context, arg.tm_year + 1900); + args[1] = JSValueMakeNumber(m_context, arg.tm_mon); + args[2] = JSValueMakeNumber(m_context, arg.tm_mday); + args[3] = JSValueMakeNumber(m_context, arg.tm_hour); + args[4] = JSValueMakeNumber(m_context, arg.tm_min); + args[5] = JSValueMakeNumber(m_context, arg.tm_sec); + + JSValueRef exception = NULL; + JSObjectRef result = JSObjectMakeDate(m_context, 6, args, &exception); + if (NULL != exception) { + ThrowMsg(ConversionException, "Couldn't convert to a JS Date."); + } + + return result; +} + +JSValueRef Converter::toJSValueRef(const time_t arg) +{ + struct tm tminfo; + memset(&tminfo,0,sizeof(tminfo)); + localtime_r(&arg, &tminfo); + return toJSValueRef(tminfo); +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(const char* arg) +{ + return toJSValueRef(std::string(arg)); +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(JSValueRef arg) +{ + return arg; +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSStringRef Converter::toJSStringRef(const std::string& arg) +{ + return JSStringCreateWithUTF8CString(arg.c_str()); +} + +double Converter::toNumber_(const JSStringRef& arg) +{ + return toNumber_(toString(arg)); +} + +double Converter::toNumber_(const std::string& arg) +{ + double result; + std::stringstream ss(arg); + if (!(ss >> result)) { + Throw(ConversionException); + } + return result; +} + +double Converter::toNumber_(const JSValueRef& arg) +{ + JSValueRef exception = NULL; + double result = JSValueToNumber(m_context, arg, &exception); + if (NULL != exception) { + ThrowMsg(ConversionException, "Couldn't convert to a number."); + } + return result; +} + +std::string Converter::toString_(const JSValueRef& arg) +{ + std::string result; + + JSValueRef exception = NULL; + JSStringRef str = JSValueToStringCopy(m_context, arg, &exception); + if (NULL == str) { + ThrowMsg(ConversionException, "Couldn't cast to a string."); + } + + size_t jsSize = JSStringGetMaximumUTF8CStringSize(str); + if (jsSize > 0) { + DPL::ScopedArray buffer(new char[jsSize]); + JSStringGetUTF8CString(str, buffer.Get(), jsSize); + result = buffer.Get(); + } + JSStringRelease(str); + return result; +} + +bool Converter::isNan(double value) const +{ + // This should work unless -ffast-math (GCC) option is used. + STATIC_CHECK(std::numeric_limits::is_iec559, + NOT_IEEE754_REPRESENTATION); + return (value != value); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src_mobile/CommonsJavaScript/Converter.h b/src_mobile/CommonsJavaScript/Converter.h new file mode 100644 index 0000000..ff196b6 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Converter.h @@ -0,0 +1,585 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class Converter : private DPL::Noncopyable +{ + public: + explicit Converter(JSContextRef context); + virtual ~Converter(); + + /** + * Converts JSValueRef to JSObjectRef. + * @param arg JSValueRef object to convert. + * @return JSObjectRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSObjectRef toJSObjectRef(const JSValueRef& arg); + + /** + * Converts JSValueRef object to boolean value. + * @param arg JSValueRef object to convert. + * @return Boolean value. + * @throw ConversionException Thrown when conversion fails. + */ + bool toBool(const JSValueRef& arg); + + /** + * Converts JSValueRef object to unsigned char value. + * @param arg JSValueRef object to convert. + * @return Unsigned char value. + * @throw ConversionException Thrown when conversion fails. + */ + unsigned char toUChar(const JSValueRef& arg); + + /** + * Converts JSValueRef object to char value. + * @param arg JSValueRef object to convert. + * @return Char value. + * @throw ConversionException Thrown when conversion fails. + */ + char toChar(const JSValueRef& arg); + + /** + * Converts JSValueRef to integer value. + * @param arg JSValueRef object to convert. + * @return Integer value. + * @throw ConversionException Thrown when conversion fails. + */ + int toInt(const JSValueRef& arg); + + /** + * Converts string to integer value. + * @param arg string to convert. + * @return Integer value. + * @throw ConversionException Thrown when conversion fails. + */ + int toInt(const std::string& arg); + + /** + * Converts JSvalueRef to long integer value. + * @param arg JSValueRef object to convert. + * @return Long integer value. + * @throw ConversionException Thrown when conversion fails. + */ + long toLong(const JSValueRef& arg); + + /** + * Converts JSvalueRef to long long integer value. + * @param arg JSValueRef object to convert. + * @return Long long integer value. + * @throw ConversionException Thrown when conversion fails. + */ + long long toLongLong(const JSValueRef& arg); + /** + * Converts JSValueRef to unsigned long value. + * @param arg JSValueRef object to convert. + * @return Unsigned long value. + * @throw ConversionException Thrown when conversion fails. + */ + unsigned long toULong(const JSValueRef& arg); + + /** + * Converts JSValueRef to double value. + * @param arg JSValueRef object to convert. + * @return Double value. + * @throw ConversionException Thrown when conversion fails. + */ + double toDouble(const JSValueRef& arg); + + /** + * Converts JSValueRef to size_t value. + * @param arg JSValueRef object to convert. + * @return Size_t value. + * @throw ConversionException Thrown when conversion fails. + */ + std::size_t toSizeT(const JSValueRef& arg); + + /** + * Converts JSStringRef to size_t value. + * @param arg JSStringRef object to convert. + * @return Size_t value. + * @throw ConversionException Thrown when conversion fails. + */ + std::size_t toSizeT(const JSStringRef& arg); + + /** + * Converts int to STL string. + * @param arg int to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toString(int arg); + + std::string toString(unsigned long arg); + + std::string toString(long arg); + + std::string toString(std::size_t arg); + + /** + * Converts JSValueRef to STL string. + * @param arg JSValueRef to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + * @remarks If one wants to convert JS Date object to a string then + * toDateString() should be used. + */ + std::string toString(const JSValueRef& arg); + + /** + * Converts JSStringRef to STL string. + * @param arg JSStringRef to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toString(const JSStringRef& arg); + + /** + * Converts JSSValueRef to STL string if + * arg is one of: String, Number, Bool + * @param arg JSValueReg to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string tryString(const JSValueRef& arg); + + /** + * Converts JS Date object to STL string. + * @param arg JS Date object to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toDateString(const JSValueRef& arg); + + /** + * Converts JSValueRef to time_t value. + * @param arg JSValueRef to convert. + * @return time_t value. + * @throw ConversionException Thrown when conversion fails. + */ + time_t toDateTimeT(const JSValueRef& arg); + + /** + * Converts JSValueRef to tm struct. + * @param arg JSValueRef to convert. + * @return tm struct. + * @throw ConversionException Thrown when conversion fails. + */ + tm toDateTm(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector. + * @param arg JSValueRef to convert. + * @return vector. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfUChars(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector. + * @param arg JSValueRef to convert. + * @return vector. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfChars(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector. + * @param arg JSValueRef to convert. + * @return vector. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfInts(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector of string. + * @param arg JSValueRef to convert. + * @return std::vector + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfStrings(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector of time_t. + * @param arg JSValueRef to convert. + * @return std::vector + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfTimeT(const JSValueRef& arg); + + /** + * Converts boolean value to JSValueRef. + * @param arg Boolean value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(bool arg); + + /** + * Converts integer value to JSValueRef. + * @param arg Integer value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(int arg); + + /** + * Converts unsigned integer value to JSValueRef. + * @param arg Unsigned integer value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(unsigned int arg); + + /** + * Converts double value to JSValueRef. + * @param arg Double value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(double arg); + + /** + * Converts unsigned long value to JSValueRef. + * @param arg unsigned long value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(unsigned long arg); + + /** + * Converts long value to JSValueRef. + * @param arg long value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRefLong(const long arg); + + /** + * Converts unsigned long value to JSValueRef. + * @param arg long long int value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(long long int arg); + + /** + * Converts STL string to JSValueRef. + * @param arg STL string to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::string& arg); + + /** + * Converts char sequence to JSValueRef. + * @param arg char sequence to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const char* arg); + + /** + * Converts time_t value to JSValueRef. + * @param arg time_t value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const time_t arg); + + /** + * Converts tm struct to JSValueRef. + * @param arg tm struct to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const tm& arg); + + /** + * Converts STL vector of integer to JSValueRef. + * @param arg STL vector of integer to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Converts STL vector of time_t to JSValueRef. + * @param arg STL vector of time_t to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Converts STL vector of string to JSStringRef. + * @param arg STL string to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Converts JSValueRef to JSValueRef + * @param JSValueRef js value which is returned + * @return JSValueRef - parameter + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(JSValueRef arg); + + /** + * Converts std::vector to JSValueRef + * @param arg vecotr of JSValueRefs + * @return JSValueRef - js array + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Template specialization to catch errors caused + * by wrong usage of general template or + * implicit conversions from SharedPtr to + * specialized type + * */ + template + JSValueRef toJSValueRef(const DPL::SharedPtr& c) + { + STATIC_ERROR(ERROR_INVALID_IMPLICIT_CONVERSION, c) + //above macro causes compilation error + return static_cast(NULL); + } + + /** + * Converts STL string to JSStringRef. + * @param arg STL string to convert. + * @return JSStringRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSStringRef toJSStringRef(const std::string& arg); + + protected: + bool isNan(double value) const; + + double toNumber_(const JSValueRef& arg); + + double toNumber_(const JSStringRef& arg); + + double toNumber_(const std::string& arg); + + template + std::vector toVectorOfT_(const JSValueRef& arg, + T (Derived::*f)(const JSValueRef &), + Derived* object) + { + if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) + { + return std::vector(); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "Argument is not an JS array."); + } + + std::vector result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back((object->*f)(element)); + } + return result; + } + + template + std::vector toVectorOfT_(const JSValueRef& arg, + T (Converter::*f)(const JSValueRef &)) + { + if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) + { + return std::vector(); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "Argument is not an JS array."); + } + + std::vector result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back((this->*f)(element)); + } + return result; + } + + template + JSValueRef toJSValueRef_(const std::vector& arg, + JSValueRef (Derived::*f)(const T &), + Derived* object) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = (object->*f)(arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template + JSValueRef toJSValueRef_(const std::vector& arg) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = toJSValueRef(arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template + JSValueRef toJSValueRef_(const std::list& arg) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + typename std::list::const_iterator it = arg.begin(); + for (std::size_t i = 0; it != arg.end(); ++i, ++it) { + JSValueRef tmpVal = toJSValueRef(*it); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template + JSValueRef toJSValueRef_(const std::list& arg, + JSValueRef (Derived::*f)(const T &), + Derived* object) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + typename std::list::const_iterator it = arg.begin(); + for (std::size_t i = 0; it != arg.end(); ++i, ++it) { + JSValueRef tmpVal = (object->*f)(*it); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + std::string toString_(const JSValueRef& arg); + + template + std::string toString_(const T& arg) + { + std::stringstream ss; + if (!(ss << arg)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, + "Could not convert to string."); + } + return ss.str(); + } + + protected: + JSContextRef m_context; +}; + +template +class ConverterFactory : private DPL::Noncopyable +{ + public: + /** + * Converter type which deletes itself when gets out of scope. + */ + typedef DPL::SharedPtr ConverterType; + + public: + /** + * Gets converter object. + * @param context JavaScript context the conversion will be performed in. + * @param[out] exception JavaScript value for storing exception. + * @return Converter object. + */ + static ConverterType getConverter(JSContextRef context) + { + C* convert = new C(context); + return ConverterType(convert); + } + + private: + ConverterFactory(); +}; + +typedef ConverterFactory BasicConverterFactory; + +typedef BasicConverterFactory::ConverterType BasicConverter; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ */ diff --git a/src_mobile/CommonsJavaScript/DESCRIPTION b/src_mobile/CommonsJavaScript/DESCRIPTION new file mode 100644 index 0000000..7f04546 --- /dev/null +++ b/src_mobile/CommonsJavaScript/DESCRIPTION @@ -0,0 +1 @@ +Common code diff --git a/src_mobile/CommonsJavaScript/DOMExceptionData.cpp b/src_mobile/CommonsJavaScript/DOMExceptionData.cpp new file mode 100644 index 0000000..3eb148a --- /dev/null +++ b/src_mobile/CommonsJavaScript/DOMExceptionData.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "DOMExceptionData.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +DOMExceptionData::DOMExceptionData(int code, + const std::string& message) : + m_code(code), + m_message(message) +{} + +int DOMExceptionData::getCode() const +{ + return m_code; +} + +std::string DOMExceptionData::getMessage() const +{ + return m_message; +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_mobile/CommonsJavaScript/DOMExceptionData.h b/src_mobile/CommonsJavaScript/DOMExceptionData.h new file mode 100644 index 0000000..b6cd760 --- /dev/null +++ b/src_mobile/CommonsJavaScript/DOMExceptionData.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_DOM_EXCEPTION_DATA_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_DOM_EXCEPTION_DATA_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class DOMExceptionData +{ + public: + explicit DOMExceptionData(int code, + const std::string& message = std::string()); + + int getCode() const; + std::string getMessage() const; + + private: + int m_code; + std::string m_message; +}; + +typedef DPL::SharedPtr DOMExceptionDataPtr; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // WRT_DOM_EXCEPTION_DATA_H_ diff --git a/src_mobile/CommonsJavaScript/JSCallbackManager.cpp b/src_mobile/CommonsJavaScript/JSCallbackManager.cpp new file mode 100644 index 0000000..56373e3 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSCallbackManager.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file JSCalendar.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#include "JSCallbackManager.h" +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +JSCallbackManagerPtr JSCallbackManager::createObject( + JSContextRef context, + JSValueRef onSuccess, + JSValueRef onError, + bool + acceptJSNullAsOnSuccess, + bool acceptJSNullAsOnError) +{ + JSObjectRef l_onSuccess = NULL; + JSObjectRef l_onError = NULL; + + if (NULL != onSuccess && + (!acceptJSNullAsOnSuccess || !JSValueIsNull(context, onSuccess))) + { + l_onSuccess = JSValueToObject(context, onSuccess, NULL); + if (!l_onSuccess || + !JSObjectIsFunction(context, l_onSuccess)) + { + ThrowMsg(Commons::InvalidArgumentException, + "success callback is not a function"); + } + } else { + //LogWarning("onSuccessCallback is NULL and is not registred"); + } + if (NULL != onError && + (!acceptJSNullAsOnError || !JSValueIsNull(context, onError))) + { + l_onError = JSValueToObject(context, onError, NULL); + if (!l_onError || + !JSObjectIsFunction(context, l_onError)) + { + ThrowMsg(Commons::InvalidArgumentException, + "error callback is not a function"); + } + } else { + //LogWarning("onErrorCallback is NULL and is not registred"); + } + return JSCallbackManagerPtr(new JSCallbackManager(context, l_onSuccess, + l_onError)); +} + +JSCallbackManager::JSCallbackManager(JSContextRef context, + JSObjectRef onSuccess, + JSObjectRef onError) : + m_onSuccess(NULL), + m_onError(NULL), + m_context(context), + m_object(NULL) +{ + setOnSuccess(onSuccess); + setOnError(onError); +} + +JSCallbackManager::~JSCallbackManager() +{ + if (m_onSuccess) { + JSValueUnprotect(m_context, m_onSuccess); + } + + if (m_onError) { + JSValueUnprotect(m_context, m_onError); + } + + if (m_object) { + JSValueUnprotect(m_context, m_object); + } +} + +void JSCallbackManager::setOnSuccess(JSValueRef onSuccess) +{ + if (m_onSuccess != NULL) { + JSValueUnprotect(m_context, m_onSuccess); + } + + if (onSuccess) { + m_onSuccess = JSValueToObject(m_context, onSuccess, NULL); + } else { + m_onSuccess = NULL; + } + + if (m_onSuccess != NULL) { + JSValueProtect(m_context, m_onSuccess); + } +} + +JSValueRef JSCallbackManager::getOnSuccess() const +{ + return m_onSuccess; +} + +void JSCallbackManager::setOnError(JSValueRef onError) +{ + if (m_onError != NULL) { + JSValueUnprotect(m_context, m_onError); + } + + if (onError) { + m_onError = JSValueToObject(m_context, onError, NULL); + } else { + m_onError = NULL; + } + + if (m_onError != NULL) { + JSValueProtect(m_context, m_onError); + } +} + +JSValueRef JSCallbackManager::getOnError() const +{ + return m_onError; +} + +void JSCallbackManager::setObject(JSObjectRef object) +{ + if (m_object != NULL) { + JSValueUnprotect(m_context, m_object); + } + + m_object = object; + + if (m_object != NULL) { + JSValueProtect(m_context, m_object); + } +} + +JSObjectRef JSCallbackManager::getObject() const +{ + return m_object; +} + +void JSCallbackManager::setContext(JSContextRef context) +{ + m_context = context; +} + +void JSCallbackManager::callOnSuccess() +{ + if (m_onSuccess == NULL) { + //LogDebug("Success callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onSuccess, NULL, 0); +} + +void JSCallbackManager::callOnSuccess(JSValueRef obj) +{ + if (m_onSuccess == NULL) { + //LogDebug("Success callback is not set"); + return; + } + JSValueRef objParam[1] = { obj }; + makeCallback(m_context, NULL, m_onSuccess, objParam, 1); +} + +void JSCallbackManager::callOnSuccess(JSValueRef obj[], + int paramCount) +{ + if (m_onSuccess == NULL) { + //LogDebug("Success callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onSuccess, obj, paramCount); +} + +void JSCallbackManager::callOnError() +{ + if (m_onError == NULL) { + //LogDebug("Error callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onError, NULL, 0); +} + +void JSCallbackManager::callOnError(JSValueRef obj) +{ + if (m_onError == NULL) { + //LogDebug("Error callback is not set"); + return; + } + JSValueRef objParam[1] = { obj }; + makeCallback(m_context, NULL, m_onError, objParam, 1); +} + +void JSCallbackManager::callOnError(JSValueRef obj[], + int paramCount) +{ + if (m_onError == NULL) { + //LogDebug("Error callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onError, obj, paramCount); +} + +void JSCallbackManager::makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + JSValueRef argv[], + unsigned argc) +{ + if (callback == NULL) { + //LogError("callback is 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; + } +} +} +} diff --git a/src_mobile/CommonsJavaScript/JSCallbackManager.h b/src_mobile/CommonsJavaScript/JSCallbackManager.h new file mode 100644 index 0000000..457fe95 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSCallbackManager.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file JSCallbackManager.h + * @author Lukasz Marek (l.marel@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSCallbackManager; +typedef DPL::SharedPtr JSCallbackManagerPtr; + +class JSCallbackManager : public WrtDeviceApis::Commons::IEventPrivateData +{ + private: + JSCallbackManager() + {} + + /** + * Used to create JSCallbackManagerPtr object by factory method + * createObject + */ + JSCallbackManager(JSContextRef context, + JSObjectRef onSuccess, + JSObjectRef onError); + + public: + + //JSCallbackManager( JSContextRef context, JSValueRef onSuccess, JSValueRef + // onError ); + + /** + * Create JSCallbackManagerPtr object witch checking callback parameters + * if callbacks are NULL it was programmer intention to not use callback and + * no exception will be rised + * if callbacks are some object but not a function it will rise exception + * @param[in] context - global context + * @param[in] onSuccess - success callback (may be NULL if not needed) + * @param[in] onError - error callback (may be NULL if not needed) + * @param[in] acceptJSNullAsOnSuccess - converts JSNull on onSuccess to NULL + * when true + * @param[in] acceptJSNullAsOnError - converts JSNull on onError to NULL + * when true + * @throw Commons::InvalidArgumentException - if callback is not null and is + * not a js function + */ + static JSCallbackManagerPtr createObject( + JSContextRef context, + JSValueRef onSuccess = NULL, + JSValueRef onError = NULL, + bool acceptJSNullAsOnSuccess = false, + bool acceptJSNullAsOnError = false); + + virtual ~JSCallbackManager(); + + void setContext(JSContextRef context); + + JSContextRef getContext() const + { + return m_context; + } + + void setOnSuccess(JSValueRef onSuccess); + JSValueRef getOnSuccess() const; + void setOnError(JSValueRef onError); + JSValueRef getOnError() const; + void setObject(JSObjectRef object); + JSObjectRef getObject() const; + + void callOnSuccess(); + void callOnSuccess(JSValueRef obj); + void callOnSuccess(JSValueRef obj[], int paramCount); + + void callOnError(); + void callOnError(JSValueRef obj); + void callOnError(JSValueRef obj[], int paramCount); + + private: + void makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + JSValueRef argv[], + unsigned argc); + + JSObjectRef m_onSuccess; + JSObjectRef m_onError; + JSContextRef m_context; + JSObjectRef m_object; +}; + +bool isCallback(JSContextRef ctx, + JSValueRef value, + JSValueRef* exception); +} +} + +#endif // WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ diff --git a/src_mobile/CommonsJavaScript/JSDOMException.cpp b/src_mobile/CommonsJavaScript/JSDOMException.cpp new file mode 100644 index 0000000..ffee065 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSDOMException.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "JSDOMException.h" + +#include + +#include "Converter.h" + +namespace { +const char* PLUGIN_NAME = "DOMException"; +const char* PROPERTY_CODE = "code"; +const char* PROPERTY_MESSAGE = "message"; + +struct Error +{ + const char* name; + const unsigned short value; +}; +// This array CAN'T be left empty! +const Error PROPERTY_ERROR[] = { + { "UNKNOWN_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::UNKNOWN_ERR }, + { "INDEX_SIZE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INDEX_SIZE_ERR }, + { "DOMSTRING_SIZE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::DOMSTRING_SIZE_ERR }, + { "HIERARCHY_REQUEST_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + HIERARCHY_REQUEST_ERR }, + { "WRONG_DOCUMENT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::WRONG_DOCUMENT_ERR }, + { "INVALID_CHARACTER_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INVALID_CHARACTER_ERR }, + { "NO_DATA_ALLOWED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + NO_DATA_ALLOWED_ERR }, + { "NO_MODIFICATION_ALLOWED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + NO_MODIFICATION_ALLOWED_ERR }, + { "NOT_FOUND_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NOT_FOUND_ERR }, + { "NOT_SUPPORTED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NOT_SUPPORTED_ERR }, + { "INUSE_ATTRIBUTE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INUSE_ATTRIBUTE_ERR }, + { "INVALID_STATE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_STATE_ERR }, + { "SYNTAX_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::SYNTAX_ERR }, + { "INVALID_MODIFICATION_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INVALID_MODIFICATION_ERR }, + { "NAMESPACE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NAMESPACE_ERR }, + { "INVALID_ACCESS_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_ACCESS_ERR }, + { "VALIDATION_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::VALIDATION_ERR }, + { "TYPE_MISMATCH_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::TYPE_MISMATCH_ERR }, + { "SECURITY_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::SECURITY_ERR }, + { "NETWORK_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NETWORK_ERR }, + { "ABORT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::ABORT_ERR }, + { "TIMEOUT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::TIMEOUT_ERR }, + { "INVALID_VALUES_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_VALUES_ERR }, + { "IO_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::IO_ERR }, + { "QUOTA_EXCEEDED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::QUOTA_EXCEEDED_ERR } +}; +} // namespace + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +JSClassRef JSDOMException::m_classRef = NULL; + +JSClassDefinition JSDOMException::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + NULL, //__function, + initialize, + finalize, + hasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSDOMException::m_properties[] = { + { PROPERTY_CODE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MESSAGE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSDOMException::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSDOMException::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSDOMException::initialize(JSContextRef /*context*/, + JSObjectRef /*object*/) +{} + +void JSDOMException::finalize(JSObjectRef object) +{ + PrivateObject* privateObject = + static_cast(JSObjectGetPrivate(object)); + if (privateObject) { + JSObjectSetPrivate(object, NULL); + delete privateObject; + } +} + +bool JSDOMException::hasProperty(JSContextRef /*context*/, + JSObjectRef /*object*/, + JSStringRef propertyName) +{ + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_ERROR[i].name)) + { + return true; + } + } + return false; +} + +JSValueRef JSDOMException::getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + PrivateObject* privateObject = + static_cast(JSObjectGetPrivate(object)); + if (!privateObject) { + LogError("Private object is not set."); + return JSValueMakeUndefined(context); + } + + Converter converter(context); + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_CODE)) { + return converter.toJSValueRef(privateObject->getObject()->getCode()); + } else if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_MESSAGE)) + { + return converter.toJSValueRef( + privateObject->getObject()->getMessage()); + } + } catch (const Commons::ConversionException& ex) { + LogError("Exception: " << ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSDOMException::getProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + Converter converter(context); + try { + std::string prop = converter.toString(propertyName); + + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (prop == PROPERTY_ERROR[i].name) { + return converter.toJSValueRef(PROPERTY_ERROR[i].value); + } + } + } catch (const Commons::ConversionException& ex) { + LogError("Exception: " << ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +void JSDOMException::getPropertyNames( + JSContextRef /*context*/, + JSObjectRef /*object*/, + JSPropertyNameAccumulatorRef accumulator) +{ + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + JSPropertyNameAccumulatorAddName(accumulator, + JSStringCreateWithUTF8CString( + PROPERTY_ERROR[i].name)); + } +} + +bool JSDOMException::hasInstance(JSContextRef context, + JSObjectRef /*constructor*/, + JSValueRef possibleInstance, + JSValueRef* /*exception*/) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src_mobile/CommonsJavaScript/JSDOMException.h b/src_mobile/CommonsJavaScript/JSDOMException.h new file mode 100644 index 0000000..dcea1e4 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSDOMException.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_DOM_EXCEPTION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_DOM_EXCEPTION_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSDOMException +{ + public: + typedef PrivateObjectT::Type PrivateObject; + + public: + static const unsigned short UNKNOWN_ERR = 0; + static const unsigned short INDEX_SIZE_ERR = 1; + static const unsigned short DOMSTRING_SIZE_ERR = 2; + static const unsigned short HIERARCHY_REQUEST_ERR = 3; + static const unsigned short WRONG_DOCUMENT_ERR = 4; + static const unsigned short INVALID_CHARACTER_ERR = 5; + static const unsigned short NO_DATA_ALLOWED_ERR = 6; + static const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7; + static const unsigned short NOT_FOUND_ERR = 8; + static const unsigned short NOT_SUPPORTED_ERR = 9; + static const unsigned short INUSE_ATTRIBUTE_ERR = 10; + static const unsigned short INVALID_STATE_ERR = 11; + static const unsigned short SYNTAX_ERR = 12; + static const unsigned short INVALID_MODIFICATION_ERR = 13; + static const unsigned short NAMESPACE_ERR = 14; + static const unsigned short INVALID_ACCESS_ERR = 15; + static const unsigned short VALIDATION_ERR = 16; + static const unsigned short TYPE_MISMATCH_ERR = 17; + static const unsigned short SECURITY_ERR = 18; + static const unsigned short NETWORK_ERR = 19; + static const unsigned short ABORT_ERR = 20; + static const unsigned short TIMEOUT_ERR = 21; + static const unsigned short INVALID_VALUES_ERR = 22; + static const unsigned short IO_ERR = 100; + + //TODO INVALID_VALUES_ERR has the same error code ?? + static const unsigned short QUOTA_EXCEEDED_ERR = 22; + + public: + static JSClassRef getClassRef(); + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static void getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef accumulator); + + /** + * The callback invoked when an object is used as the target of an + * 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + static JSClassRef m_classRef; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // + diff --git a/src_mobile/CommonsJavaScript/JSDOMExceptionFactory.cpp b/src_mobile/CommonsJavaScript/JSDOMExceptionFactory.cpp new file mode 100644 index 0000000..94c1797 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSDOMExceptionFactory.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "JSDOMExceptionFactory.h" + +#include +#include + +#include "JSUtils.h" +#include "DOMExceptionData.h" +#include "JSDOMException.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +#define DEFINE_JS_EXCEPTION_FACTORY(Class, Code) \ + JSDOMExceptionFactory JSDOMExceptionFactory::Class(Code) + +DEFINE_JS_EXCEPTION_FACTORY(UnknownException, JSDOMException::UNKNOWN_ERR); +DEFINE_JS_EXCEPTION_FACTORY(IndexSizeException, JSDOMException::INDEX_SIZE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(DomstringSizeException, + JSDOMException::DOMSTRING_SIZE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(HierarchyRequestException, + JSDOMException::HIERARCHY_REQUEST_ERR); +DEFINE_JS_EXCEPTION_FACTORY(WrongDocumentException, + JSDOMException::WRONG_DOCUMENT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidCharacterException, + JSDOMException::INVALID_CHARACTER_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NoDataAllowedException, + JSDOMException::NO_DATA_ALLOWED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NoModificationAllowedException, + JSDOMException::NO_MODIFICATION_ALLOWED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NotFoundException, JSDOMException::NOT_FOUND_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NotSupportedException, + JSDOMException::NOT_SUPPORTED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InuseAttributeException, + JSDOMException::INUSE_ATTRIBUTE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidStateException, + JSDOMException::INVALID_STATE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(SyntaxException, JSDOMException::SYNTAX_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidModificationException, + JSDOMException::INVALID_MODIFICATION_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NamespaceException, JSDOMException::NAMESPACE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidAccessException, + JSDOMException::INVALID_ACCESS_ERR); +DEFINE_JS_EXCEPTION_FACTORY(ValidationException, JSDOMException::VALIDATION_ERR); +DEFINE_JS_EXCEPTION_FACTORY(TypeMismatchException, + JSDOMException::TYPE_MISMATCH_ERR); +DEFINE_JS_EXCEPTION_FACTORY(SecurityException, JSDOMException::SECURITY_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NetworkException, JSDOMException::NETWORK_ERR); +DEFINE_JS_EXCEPTION_FACTORY(AbortException, JSDOMException::ABORT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(TimeoutException, JSDOMException::TIMEOUT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidValuesException, + JSDOMException::INVALID_VALUES_ERR); +DEFINE_JS_EXCEPTION_FACTORY(IOException, JSDOMException::IO_ERR); +DEFINE_JS_EXCEPTION_FACTORY(QuotaExceededException, + JSDOMException::QUOTA_EXCEEDED_ERR); + +JSDOMExceptionFactory::JSDOMExceptionFactory(int code) : m_code(code) +{} + +JSValueRef JSDOMExceptionFactory::make(JSContextRef context, + JSValueRef* exception, + const std::string& message) +{ + Assert(exception && "Exception object can't be NULL."); + JSDOMException::PrivateObject::ObjectType data(new DOMExceptionData(m_code, + message)); + *exception = JSUtils::makeObject(context, + JSDOMException::getClassRef(), + data); + return JSValueMakeUndefined(context); +} + +JSObjectRef JSDOMExceptionFactory::make(JSContextRef context, + const std::string& message) +{ + JSDOMException::PrivateObject::ObjectType data(new DOMExceptionData(m_code, + message)); + return JSUtils::makeObject(context, + JSDOMException::getClassRef(), data); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_mobile/CommonsJavaScript/JSDOMExceptionFactory.h b/src_mobile/CommonsJavaScript/JSDOMExceptionFactory.h new file mode 100644 index 0000000..2bf8329 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSDOMExceptionFactory.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRT_DOM_EXCEPTION_FACTORY_H_ +#define WRT_DOM_EXCEPTION_FACTORY_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +#define DECLARE_JS_EXCEPTION_FACTORY(Class) static JSDOMExceptionFactory Class + +class JSDOMExceptionFactory : public DPL::Noncopyable +{ + public: + DECLARE_JS_EXCEPTION_FACTORY(UnknownException); + DECLARE_JS_EXCEPTION_FACTORY(IndexSizeException); + DECLARE_JS_EXCEPTION_FACTORY(DomstringSizeException); + DECLARE_JS_EXCEPTION_FACTORY(HierarchyRequestException); + DECLARE_JS_EXCEPTION_FACTORY(WrongDocumentException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidCharacterException); + DECLARE_JS_EXCEPTION_FACTORY(NoDataAllowedException); + DECLARE_JS_EXCEPTION_FACTORY(NoModificationAllowedException); + DECLARE_JS_EXCEPTION_FACTORY(NotFoundException); + DECLARE_JS_EXCEPTION_FACTORY(NotSupportedException); + DECLARE_JS_EXCEPTION_FACTORY(InuseAttributeException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidStateException); + DECLARE_JS_EXCEPTION_FACTORY(SyntaxException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidModificationException); + DECLARE_JS_EXCEPTION_FACTORY(NamespaceException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidAccessException); + DECLARE_JS_EXCEPTION_FACTORY(ValidationException); + DECLARE_JS_EXCEPTION_FACTORY(TypeMismatchException); + DECLARE_JS_EXCEPTION_FACTORY(SecurityException); + DECLARE_JS_EXCEPTION_FACTORY(NetworkException); + DECLARE_JS_EXCEPTION_FACTORY(AbortException); + DECLARE_JS_EXCEPTION_FACTORY(TimeoutException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidValuesException); + DECLARE_JS_EXCEPTION_FACTORY(IOException); + DECLARE_JS_EXCEPTION_FACTORY(QuotaExceededException); + + public: + explicit JSDOMExceptionFactory(int code); + + /** + * Creates exception object. + * @param context JS context of the exception. + * @param[out] exception Result object to which exception will be assigned. + * @return JS undefined value. + * @code + * JSValueRef JSClass::getProperty(JSContextRef context, + * JSObjectRef object, + * JSStringRef propertyName, + * JSValueRef* exception) + * { + * ... + * return JSExceptionFactory::InvalidArgumentException.make(context, + * exception); + * ... + * } + * @endcode + */ + JSValueRef make(JSContextRef context, + JSValueRef* exception, + const std::string& message = std::string()); + + /** + * Creates exception object. + * @param context JS context of the exception. + * @return JS exception object. + * @code + * JSObjectRef jsError = + * JSExceptionFactory::InvalidArgumentException.make(context); + * @endcode + */ + JSObjectRef make(JSContextRef context, + const std::string& message = std::string()); + + private: + int m_code; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // diff --git a/src_mobile/CommonsJavaScript/JSPendingOperation.cpp b/src_mobile/CommonsJavaScript/JSPendingOperation.cpp new file mode 100644 index 0000000..1891361 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSPendingOperation.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file JSPendingOperation.cpp + * @author Pete Cole (peter.cole@partner.samsung.com) + * @version 0.1 + * 0.2 k.majewski@samsung.com + * @brief Implementation of the JSPendingOperation class + */ + +#include +#include +#include "JSPendingOperation.h" +#include "JSPendingOperationPrivateObject.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +namespace { +const char* PLUGIN_NAME = "PendingOperation"; +} + +JSClassRef JSPendingOperation::m_classRef = NULL; + +JSClassDefinition JSPendingOperation::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + NULL, + m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticFunction JSPendingOperation::m_functions[] = { + { "cancel", cancel, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSPendingOperation::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSPendingOperation::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSPendingOperation::finalize(JSObjectRef object) +{ + delete static_cast( + JSObjectGetPrivate(object)); +} + +JSValueRef JSPendingOperation::cancel(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + (void) object; + (void) argumentCount; + (void) arguments; + (void) exception; + LogDebug(__FUNCTION__); + IJSPendingOperationPrivateObject *priv = + static_cast( + JSObjectGetPrivate(thisObject)); + assert(NULL != priv); + bool cancelResult = priv->cancel(); + LogDebug("cancel result : " << cancelResult); + return JSValueMakeBoolean(context, cancelResult); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src_mobile/CommonsJavaScript/JSPendingOperation.h b/src_mobile/CommonsJavaScript/JSPendingOperation.h new file mode 100644 index 0000000..1a67d89 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSPendingOperation.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file JSPendingOperation.h + * @author Pete Cole (peter.cole@partner.samsung.com) + * @version 0.1 + * 0.2 k.majewski@samsung.com + * @brief Declaration of the JSPendingOperation class + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDINGOPERATION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDINGOPERATION_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +//typedef Commons::PrivateObjectT::Type +// PendingOperationPrivateObject; + +class JSPendingOperation +{ + public: + /* + * This initializes this JS class in the JS Engine. + */ + static 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); + + /** + * 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[]; + + static JSClassRef m_classRef; + + /** + * Cancel the pending operation, if it has yet not completed. + */ + static JSValueRef cancel(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // _JS_WAC_PENDINGOPERATION_H_ + diff --git a/src_mobile/CommonsJavaScript/JSPendingOperationPrivateObject.h b/src_mobile/CommonsJavaScript/JSPendingOperationPrivateObject.h new file mode 100644 index 0000000..3f41bf2 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSPendingOperationPrivateObject.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDING_OPERATION_PRIVATE_OBJECT_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDING_OPERATION_PRIVATE_OBJECT_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class IJSPendingOperationPrivateObject +{ + public: + explicit IJSPendingOperationPrivateObject( + const DPL::SharedPtr + &event) : + m_event(event) + { + assert(NULL != m_event); + } + + virtual bool cancel() + { + LogDebug("PendingOperation tries to cancel the request"); + return m_event->cancelRequest(); + } + + virtual ~IJSPendingOperationPrivateObject() + {} + + protected: + DPL::SharedPtr m_event; +}; + +/* + * This class implements private object for JavaScript PendingOperation + * with support to external cancel function. + * + * When the cancel() method is invoked on PendingOperation, + * the OnCancelEvent() method is invoked on user object + * with apropriate * arguments. + * It allows user to perform an additional action when PendingOperation + * is destroyed. + * + * The Object which want to handle OnCancelEvent have to inherit from + * Platform::IExternEventCanceler. + * + * The cancel's handler have to be passed as second argument + * */ +template +class IJSExtCancelPendingOperationPrivateObject : + public IJSPendingOperationPrivateObject +{ + public: + IJSExtCancelPendingOperationPrivateObject( + const DPL::SharedPtr< TemplateEvent> &event, + const DPL::SharedPtr< + Commons::IExternEventCanceler > & cancel) : + IJSPendingOperationPrivateObject( + DPL::StaticPointerCast(event)), + m_canceler(cancel) + { + assert(NULL != m_canceler); + } + + virtual bool cancel() + { + bool result = IJSPendingOperationPrivateObject::cancel(); + if (!result) { + LogDebug("Controller can not cancel event, trying platform cancel"); + } else { + return result; + } + + if (m_canceler) { + LogDebug("Calling extern cancel"); + m_canceler->OnCancelEvent( + DPL::StaticPointerCast(m_event)); + } + + return result; + } + + virtual ~IJSExtCancelPendingOperationPrivateObject() + {} + + protected: + DPL::SharedPtr< Commons::IExternEventCanceler > m_canceler; +}; +} +} +#endif /* _JS_WAC_PENDING_OPERATION_PRIVATE_OBJECT_H_ */ diff --git a/src_mobile/CommonsJavaScript/JSUtils.cpp b/src_mobile/CommonsJavaScript/JSUtils.cpp new file mode 100644 index 0000000..f4c9c95 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSUtils.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "Converter.h" +#include "ScopedJSStringRef.h" +#include "JSUtils.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +using namespace WrtDeviceApis::Commons; + +bool JSUtils::hasProperty(JSStaticValue* properties, + JSStringRef name) +{ + JSStaticValue* property = properties; + while (property->name) { + if (JSStringIsEqualToUTF8CString(name, property->name)) { + return true; + } + ++property; + } + return false; +} + +JSValueRef JSUtils::getJSProperty(JSContextRef context, + JSValueRef jsValue, + const std::string &name, + JSValueRef *exception) +{ + ScopedJSStringRef jsPropName(JSStringCreateWithUTF8CString(name.c_str())); + Converter converter(context); + JSObjectRef jsObject = converter.toJSObjectRef(jsValue); + if (JSObjectHasProperty(context, jsObject, jsPropName.get())) { + return JSObjectGetProperty(context, jsObject, + jsPropName.get(), exception); + } + return NULL; +} + +JSValueRef JSUtils::getJSProperty(JSContextRef context, + JSObjectRef object, + const std::string& name) +{ + Converter converter(context); + Try { + ScopedJSStringRef propName(converter.toJSStringRef(name)); + if (JSObjectHasProperty(context, object, propName.get())) { + JSValueRef result = JSObjectGetProperty(context, + object, + propName.get(), + NULL); + if (!JSValueIsUndefined(context, result)) { + return result; + } + } + } + Catch(ConversionException) {} + return NULL; +} + +JSValueRef JSUtils::getJSPropertyOrUndefined(JSContextRef context, + JSObjectRef object, + const std::string& name) +{ + Converter converter(context); + Try { + ScopedJSStringRef propName(converter.toJSStringRef(name)); + if (JSObjectHasProperty(context, object, propName.get())) { + return JSObjectGetProperty(context, object, propName.get(), NULL); + } + } + Catch(ConversionException) {} + return JSValueMakeUndefined(context); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_mobile/CommonsJavaScript/JSUtils.h b/src_mobile/CommonsJavaScript/JSUtils.h new file mode 100644 index 0000000..5d835a1 --- /dev/null +++ b/src_mobile/CommonsJavaScript/JSUtils.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_JSUTILS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_JSUTILS_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSUtils +{ + public: + static bool hasProperty(JSStaticValue* properties, + JSStringRef name); + + /** + * Gets a property from JSObject if exists + * @return JSValueRef if property exists, NULL if not + */ + static JSValueRef getJSProperty(JSContextRef context, + JSValueRef jsValue, + const std::string &name, + JSValueRef* exception = NULL); + + static JSValueRef getJSProperty(JSContextRef context, + JSObjectRef object, + const std::string& name); + + static JSValueRef getJSPropertyOrUndefined(JSContextRef context, + JSObjectRef object, + const std::string& name); + + template + static JSObjectRef makeObject(JSContextRef context, + JSClassRef classRef, + C data) + { + typedef typename PrivateObjectT::Type Private; + + Private* priv = new Private(context, data); + JSObjectRef object = JSObjectMake(context, classRef, priv); + if (!object) { + ThrowMsg(Commons::NullPointerException, + "Could not create JS object."); + } + + return object; + } + + static JSObjectRef makeObject(JSContextRef context, + JSClassRef classRef) + { + typedef PrivateObjectT::Type Private; + + Private* priv = new Private(context); + JSObjectRef object = JSObjectMake(context, classRef, priv); + if (!object) { + ThrowMsg(Commons::NullPointerException, + "Could not create JS object."); + } + + return object; + } +}; // JSUtils +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTPLUGINS_COMMONS_JSUTILS_H_ */ diff --git a/src_mobile/CommonsJavaScript/PrivateObject.h b/src_mobile/CommonsJavaScript/PrivateObject.h new file mode 100644 index 0000000..8bd816a --- /dev/null +++ b/src_mobile/CommonsJavaScript/PrivateObject.h @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_PRIVATEOBJECT_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_PRIVATEOBJECT_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template +struct NoAcquire +{ + void acquire(T*) + {} + + protected: + ~NoAcquire() + {} +}; + +template +struct AcquireByProtect +{ + void acquire(T* object) + { + Assert(object && "Object passed to protect can't be NULL."); + JSValueProtect(object->getContext(), object->getObject()); + } + + protected: + ~AcquireByProtect() + {} +}; + +template +struct NoRelease +{ + void release(T* object) + { + (void)object; + } + + protected: + ~NoRelease() + {} +}; + +template +struct ReleaseByDelete +{ + void release(T* object) + { + delete object->getObject(); + } + + protected: + ~ReleaseByDelete() + {} +}; + +template +struct ReleaseByUnprotect +{ + void release(T* object) + { + Assert(object && "Object passed to unprotect can't be NULL."); + JSValueUnprotect(object->getContext(), object->getObject()); + } + + protected: + ~ReleaseByUnprotect() + {} +}; + +template +struct NoOwnership : protected NoAcquire, + protected NoRelease +{ + protected: + ~NoOwnership() + {} +}; + +template +struct OwnershipByAcquisition : protected NoAcquire, + protected ReleaseByDelete +{ + protected: + ~OwnershipByAcquisition() + {} +}; + +template +struct OwnershipByProtection : protected AcquireByProtect, + protected ReleaseByUnprotect +{ + protected: + ~OwnershipByProtection() + {} +}; + +template class OwnershipPolicy = OwnershipByAcquisition> +class PrivateObject : public DPL::Noncopyable, + protected OwnershipPolicy > +{ + public: + typedef PrivateClass ObjectType; + + public: + /** + * Creates storage object for JS private data. + * @param context JS (root/global) context. + * @param object Object to store. + * @throw NullPointerException When object is pointer and is set to NULL. + */ + PrivateObject(JSContextRef context, + const PrivateClass& object) : + m_context(context), + m_object(object) + { + Assert(NULL != m_context && "Context is NULL."); + Assert(!Commons::IsNull::value( + object) && "Object is NULL."); + this->acquire(this); + } + + /** + * Destroys instance of the object. + */ + virtual ~PrivateObject() + { + this->release(this); + } + + /** + * Gets stored JS context. + * @return JavaScript context. + */ + virtual JSContextRef getContext() const + { + return m_context; + } + + /** + * Gets stored object. + * @return Stored object. + */ + virtual PrivateClass getObject() const + { + return m_object; + } + + protected: + JSContextRef m_context; ///< JS context. + PrivateClass m_object; ///< Stored object. +}; + +/** + * Specialization for type void. + */ +template<> +class PrivateObject : private DPL::Noncopyable +{ + public: + /** + * Creates storage object for JS private data. + * @param context JS (root/global) context. + * @remarks Takes ownership over stored object. + */ + explicit PrivateObject(JSContextRef context) : m_context(context) + { + Assert(NULL != m_context && "Context is NULL."); + } + + /** + * Destroys instance of the object. + */ + virtual ~PrivateObject() + {} + + /** + * Gets stored JS context. + * @return JavaScript context. + */ + virtual JSContextRef getContext() const + { + return m_context; + } + + protected: + JSContextRef m_context; +}; + +template +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; + +template +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; + +template<> +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; + +template<> +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* PRIVATEOBJECT_H_ */ diff --git a/src_mobile/CommonsJavaScript/ScopedJSStringRef.cpp b/src_mobile/CommonsJavaScript/ScopedJSStringRef.cpp new file mode 100644 index 0000000..2f0c17f --- /dev/null +++ b/src_mobile/CommonsJavaScript/ScopedJSStringRef.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ScopedJSStringRef.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +ScopedJSStringRef::ScopedJSStringRef(JSStringRef ref) : m_ref(ref) +{} + +ScopedJSStringRef::~ScopedJSStringRef() +{ + if (m_ref != NULL) { + JSStringRelease(m_ref); + } +} + +JSStringRef ScopedJSStringRef::get() const +{ + return m_ref; +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_mobile/CommonsJavaScript/ScopedJSStringRef.h b/src_mobile/CommonsJavaScript/ScopedJSStringRef.h new file mode 100644 index 0000000..d18238a --- /dev/null +++ b/src_mobile/CommonsJavaScript/ScopedJSStringRef.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * Takes ownership over JSStringRef object to call JSSTringRelease on it + * when this object goes out of scope. + */ +class ScopedJSStringRef : private DPL::Noncopyable +{ + public: + /** + * Creates this class instance. + * @param ref JSStringRef to take ownership. + * @remarks Takes ownership. + */ + ScopedJSStringRef(JSStringRef ref); + + /** + * Destroys instance. + * @remarks Releases stored JSStringRef. + */ + ~ScopedJSStringRef(); + + /** + * Gets stored JSStringRef. + * @return JSStringRef object. + * @remarks Doesn't pass ownership to caller. + */ + JSStringRef get() const; + + private: + JSStringRef m_ref; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ */ diff --git a/src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp b/src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp new file mode 100644 index 0000000..87111fd --- /dev/null +++ b/src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "SecurityFunctionDeclaration.h" +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +AceSecurityStatus aceCheckAccessSimple( + WrtDeviceApis::Commons::AceFunction aceFunction) +{ + return aceCheckAccess2 >(aceFunction); +} +} +} diff --git a/src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.h b/src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.h new file mode 100644 index 0000000..8ad1987 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Security/SecurityFunctionDeclaration.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef _FUNCTION_DECLARATION_ +#define _FUNCTION_DECLARATION_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +enum class AceSecurityStatus +{ + AccessGranted, + AccessDenied, + PrivacyDenied, + InternalError +}; + +template +class DefaultArgsVerifier +{ + public: + void operator()(WrtDeviceApis::Commons::AceFunction& aceFunction, + Args && ... args) const + { + static_assert( + WrtDeviceApis::Commons::AlwaysFalse::value, + "Please provide a specialization for these argument types!"); + } +}; + +template <> +class DefaultArgsVerifier<> +{ + public: + void operator()(WrtDeviceApis::Commons::AceFunction& /*aceFunction*/) const + {} +}; + +template +AceSecurityStatus aceCheckAccess2( + WrtDeviceApis::Commons::AceFunction aceFunction, + Args && ... args) +{ + using namespace WrtDeviceApis::Commons; + + ArgumentsVerifier argsVerify; + argsVerify(aceFunction, args ...); + + WrtAccess::CheckAccessReturnType ret = + WrtAccessSingleton::Instance().checkAccessControl(aceFunction); + + if (ret == WrtAccess::CHECK_ACCESS_PRIVILEGE_DENIED) { + LogError("Function is not allowed to run - AccessDenied"); + return AceSecurityStatus::AccessDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_PRIVACY_DENIED) { + LogError("Function is not allowed to run - PrivacyDenied"); + return AceSecurityStatus::PrivacyDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_INTERNAL_ERROR) { + LogError("InternalError"); + return AceSecurityStatus::InternalError; + } + + LogDebug("Function accepted!"); + + return AceSecurityStatus::AccessGranted; +} + +//The simplest version +AceSecurityStatus aceCheckAccessSimple( + WrtDeviceApis::Commons::AceFunction aceFunction); +} +} + +#endif // _FUNCTION_DECLARARION_ diff --git a/src_mobile/CommonsJavaScript/Security/StaticDeclaration.h b/src_mobile/CommonsJavaScript/Security/StaticDeclaration.h new file mode 100644 index 0000000..c089d50 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Security/StaticDeclaration.h @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _WRTPLUGINS_COMMONS_SRC_COMMONS_STATICDECLARATIOS_H_ +#define _WRTPLUGINS_COMMONS_SRC_COMMONS_STATICDECLARATIOS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template +class StaticDeclarations : public DPL::Noncopyable +{ + struct FunctionTriplet { + const char* name; + std::vector devCaps; + std::vector features; + }; + + public: + + typedef typename std::map ParamsMap; + + typedef std::map > > DeviceCapsMaps; + + typedef std::map FunctionsMap; + + typedef std::map + AceFunctionsMap; + + typedef std::map > FeaturesMap; + + static const std::string getParamName(const ParamType& paramId) + { + auto it = m_params.find(paramId); + + Assert(it != m_params.end() && "No such paramId"); + + return it->second; + } + + /** + * Returns set of device capabilities WITHOUT params + * for given device capability id + * */ + static WrtDeviceApis::Commons::AceDeviceCapability + getDeviceCapabilityWithoutParams(const DeviceCapType& devCapsId) + { + WrtDeviceApis::Commons::AceDeviceCapability deviceCap; + auto it = m_deviceCaps.find(devCapsId); + + Assert(it != m_deviceCaps.end() && "No such device cap"); + + deviceCap.devCapName = it->second.first; + + return deviceCap; + } + + /** + * Returns set of device capabilities with set params + * for given device capability id + * */ + static WrtDeviceApis::Commons::AceDeviceCapability + getDeviceCapability(const DeviceCapType& devCapsId) + { + auto it = m_deviceCaps.find(devCapsId); + + Assert(it != m_deviceCaps.end() && "No such dev-cap found"); + + WrtDeviceApis::Commons::AceDeviceCapability deviceCap; + deviceCap.devCapName = it->second.first; + + FOREACH(paramIt, it->second.second) + { + WrtDeviceApis::Commons::AceDeviceCapParam param( + getParamName(*paramIt), + std::string()); + + deviceCap.devCapParams.push_back(param); + } + + return deviceCap; + } + + static void addDeviceCapabilty( + const DeviceCapType& devCapsId, + WrtDeviceApis::Commons::AceFunction& aceFunction) + { + aceFunction.deviceCapabilities.push_back( + getDeviceCapability(devCapsId)); + } + + /** + * Returns names of device-capabilities base on capability id + */ + static std::string getDevCapNameById(DeviceCapType devCapId) + { + auto it = m_deviceCaps.find(devCapId); + Assert(it != m_deviceCaps.end() && "No such devcapid found!"); + return it->second.first; + } + + /** + * Sets parameter value for given paramId + */ + static bool setParamValue(WrtDeviceApis::Commons::AceFunction& function, + ParamType paramId, + DeviceCapType devCapId, + const std::string& value) + { + //get name of the deviceCaps + std::string devCapName = getDevCapNameById(devCapId); + std::string paramName = getParamName(paramId); + + //search throw all the device capabilities + FOREACH(devCapIt, function.deviceCapabilities) { + if (devCapIt->devCapName == devCapName) { + //device capability has been found + //check params + FOREACH(devParamIt, devCapIt->devCapParams) { + if (devParamIt->name == paramName) { + devParamIt->value = value; + return true; + } + } + } + } + return false; + } + /** + * Return struct Commons::AceFunction with set function name + * + * To set device capabilities you may use setDeviceCap function + * To set param value function you may use setParamValue Function + * */ + static WrtDeviceApis::Commons::AceFunction getEmptyFunction( + const FunctionType& functionId) + { + WrtDeviceApis::Commons::AceFunction function; + auto it = m_functions.find(functionId); + Assert(it != m_functions.end() && "No such a function"); + function.name = it->second.first; + + return function; + } + + /** + * The most useful Function + * Return Commons::AceFunction with filled all required fields: + * name, device caps and proper param namespace + * + * To set param value function you may use setParamValue function + * */ + static WrtDeviceApis::Commons::AceFunction getSecurityFunction( + const FunctionType& functionId) + { + WrtDeviceApis::Commons::AceFunction function; + auto it = m_functions.find(functionId); + Assert(it != m_functions.end() && "No such function found!"); + + function.name = it->second.name; + + FOREACH(featIt, it->second.features) + function.features.push_back(std::string(*featIt)); + + FOREACH(devCapIt, it->second.devCaps) { + function.deviceCapabilities.push_back( + getDeviceCapability(*devCapIt)); + } + return function; + } + + /** + * To create static map + * */ + static void createStaticAceFunctions() + { + FOREACH(functionIt, m_functions) + { + m_aceFunctions[functionIt->first] = + getSecurityFunction(functionIt->first); + } + } + + static feature_mapping_t* getFeaturesToDevCapMapping() + { + feature_mapping_t* mapping = new feature_mapping_t; + + mapping->featuresCount = m_features.size(); + mapping->features = new feature_devcaps_t[mapping->featuresCount]; + + size_t i = 0; + + FOREACH(featureIt, m_features) + { + mapping->features[i].feature_name = + strndup(featureIt->first.c_str(), featureIt->first.size() + 1); + + mapping->features[i].devCaps.devCapsCount = + featureIt->second.size(); + + mapping->features[i].devCaps.deviceCaps = + new char*[mapping->features[i].devCaps.devCapsCount]; + + for (size_t j = 0; + j < mapping->features[i].devCaps.devCapsCount; + ++j) + { + std::string dc = getDevCapNameById(featureIt->second[j]); + + mapping->features[i].devCaps.deviceCaps[j] = + strndup(dc.c_str(), dc.size() + 1); + } + + ++i; + } + + return mapping; + } + + static const devcaps_t* devcapsGetter(pfeature_mapping_t feats, + const char* featureName) + { + Assert(featureName && "Trying to extract info about NULL api feature"); + + std::string feature(featureName); + + devcaps_t* ret = NULL; + + for (size_t i = 0; i < feats->featuresCount; ++i) { + Assert(feats->features && + feats->features[i].feature_name && + "NULL api feature in feature mapping"); + + std::string feat(feats->features[i].feature_name); + + if (feature == feat) { + ret = &(feats->features[i].devCaps); + break; + } + } + + return ret; + } + + static void featuresDeinitializer(feature_mapping_t* mapping) + { + if (mapping) { + if (mapping->features) { + for (size_t i = 0; i < mapping->featuresCount; ++i) { + free(mapping->features[i].feature_name); + + devcaps_t& dc = mapping->features[i].devCaps; + + if (dc.deviceCaps) { + for (size_t j = 0; j < dc.devCapsCount; ++j) { + free(dc.deviceCaps[j]); + } + + delete[] dc.deviceCaps; + } + } + delete[] mapping->features; + } + delete mapping; + } + } + + static void getMappingInterface(feature_mapping_interface_t *mapping) + { + if (mapping) { + mapping->featGetter = + StaticDeclarations::getFeaturesToDevCapMapping; + mapping->dcGetter = StaticDeclarations::devcapsGetter; + mapping->release = StaticDeclarations::featuresDeinitializer; + } + } + + private: + static ParamsMap m_params; + static DeviceCapsMaps m_deviceCaps; + static FunctionsMap m_functions; + static AceFunctionsMap m_aceFunctions; + + static FeaturesMap m_features; +}; +} +} + +#endif diff --git a/src_mobile/CommonsJavaScript/SecurityExceptions.h b/src_mobile/CommonsJavaScript/SecurityExceptions.h new file mode 100644 index 0000000..ffc111b --- /dev/null +++ b/src_mobile/CommonsJavaScript/SecurityExceptions.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ + +#include +#include "JSDOMExceptionFactory.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * synchronously checks access status and throws JS Security exception if + * necessary + */ +#define SYNC_ACCESS_STATUS_HANDLER(status, context, exception) \ + do { \ + switch (status) \ + { \ + case AceSecurityStatus::InternalError: \ + return JSDOMExceptionFactory::UnknownException.make( \ + context, exception); \ + break; \ + \ + case AceSecurityStatus::AccessDenied: \ + return JSDOMExceptionFactory::SecurityException.make( \ + context, exception); \ + break; \ + \ + default: \ + break; \ + } \ + } while (0) + +/** + * checks access status and returns an error through JSCallbackManager if + * necessary + */ +#define ASYNC_CBM_ACCESS_STATUS_HANDLER(status, context, cbm) \ + do { \ + switch (status) \ + { \ + case AceSecurityStatus::InternalError: \ + cbm->callOnError(JSDOMExceptionFactory::UnknownException.make( \ + context)); \ + return JSValueMakeNull(context); \ + \ + case AceSecurityStatus::AccessDenied: \ + cbm->callOnError(JSDOMExceptionFactory::SecurityException.make( \ + context)); \ + return JSValueMakeNull(context); \ + \ + default: \ + break; \ + } \ + } while (0) +} +} +#endif /*WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ */ + diff --git a/src_mobile/CommonsJavaScript/SupportPendingOperation.h b/src_mobile/CommonsJavaScript/SupportPendingOperation.h new file mode 100644 index 0000000..05567e6 --- /dev/null +++ b/src_mobile/CommonsJavaScript/SupportPendingOperation.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_SUPPORT_PENDING_OPERATION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_SUPPORT_PENDING_OPERATION_H_ + +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template +class SupportPendingOperation +{ + public: + virtual T getPendingOperation() const + { + return *m_operation; + } + + virtual void setPendingOperation(const T& operation) + { + m_operation = operation; + } + + bool checkPendingOperation() const + { + return !m_operation.IsNull(); + } + + virtual ~SupportPendingOperation(){} + + protected: + DPL::Optional m_operation; +}; +} +} + +#endif diff --git a/src_mobile/CommonsJavaScript/Utils.h b/src_mobile/CommonsJavaScript/Utils.h new file mode 100644 index 0000000..d8b8f95 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Utils.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_UTILS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_UTILS_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * Creates pending operation object. + * @param context Global context. + * @param event Event or other object enclosed in shared ptr and convertible + * to @see WrtDeviceApis::Commons::IEventController. + * @return Pending operation object. + */ +template +JSObjectRef makePendingOperation(JSContextRef context, + const DPL::SharedPtr& event) +{ + Commons::IEventControllerPtr eventController = + DPL::StaticPointerCast(event); + IJSPendingOperationPrivateObject* pendingOperation = + new IJSPendingOperationPrivateObject(eventController); + return JSObjectMake(context, + JSPendingOperation::getClassRef(), pendingOperation); +} + +template +JSObjectRef makeExtCancelSupportedPendingOperation( + JSContextRef context, + const DPL::SharedPtr& event, + const DPL::SharedPtr >& + cancel) +{ + IJSPendingOperationPrivateObject* pendingOperation = + new IJSExtCancelPendingOperationPrivateObject(event, cancel); + + return JSObjectMake(context, + JSPendingOperation::getClassRef(), + pendingOperation); +} +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONSJAVASCRIPT_UTILS_H_ diff --git a/src_mobile/CommonsJavaScript/Validator.cpp b/src_mobile/CommonsJavaScript/Validator.cpp new file mode 100644 index 0000000..e73d361 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Validator.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "Validator.h" +#include +#include +#include "ScopedJSStringRef.h" +#include "Converter.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +Validator::Validator(JSContextRef context, + JSValueRef* exception) : + m_context(context), + m_exception(exception) +{ + Assert(NULL != m_context && "Context cannot be NULL."); +} + +Validator::~Validator() +{} + +bool Validator::isDate(const JSValueRef& arg) +{ + if (JSValueIsNull(m_context, + arg) || + JSValueIsUndefined(m_context, + arg) || !JSValueIsObject(m_context, arg)) + { + return false; + } + Converter converter(m_context); + Try + { + converter.toDateTm(arg); + } + Catch(Commons::ConversionException) + { + return false; + } + return true; +} + +bool +Validator::isCallback(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSObjectIsFunction(m_context, converter.toJSObjectRef(arg)); +} + +bool +Validator::checkArrayKeys(const std::vector &allowed, + JSValueRef argument) +{ + if (argument == NULL) { + return true; + } + if (!JSValueIsObject(m_context, argument)) { + return false; + } + JSObjectRef jsOptions = JSValueToObject(m_context, argument, NULL); + if (jsOptions == NULL) { + return false; + } + JSPropertyNameArrayRef jsProps = JSObjectCopyPropertyNames(m_context, + jsOptions); + if (jsProps == NULL) { + // No properties found; and empty array. + return true; + } + size_t nCount = JSPropertyNameArrayGetCount(jsProps); + bool found; + + std::list allowedJS; + for (size_t j = 0; j < allowed.size(); j++) { + allowedJS.push_back(JSStringCreateWithUTF8CString(allowed[j].c_str())); + } + + for (size_t i = 0; i < nCount; i++) { + found = false; + for (std::list::const_iterator it = allowedJS.begin(); + it != allowedJS.end(); + ++it) + { + if (JSStringIsEqual(*it, + JSPropertyNameArrayGetNameAtIndex(jsProps, + i))) + { + found = true; + break; + } + } + if (!found) { + for (size_t j = 0; j < allowed.size(); j++) { + JSStringRelease(allowedJS.front()); + allowedJS.pop_front(); + } + JSPropertyNameArrayRelease(jsProps); + return false; + } + } + + for (size_t j = 0; j < allowed.size(); j++) { + JSStringRelease(allowedJS.front()); + allowedJS.pop_front(); + } + JSPropertyNameArrayRelease(jsProps); + return true; +} + +bool Validator::isNullOrUndefined(const JSValueRef& arg) +{ + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg)); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_mobile/CommonsJavaScript/Validator.h b/src_mobile/CommonsJavaScript/Validator.h new file mode 100644 index 0000000..6a89550 --- /dev/null +++ b/src_mobile/CommonsJavaScript/Validator.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_VALIDATOR_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_VALIDATOR_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class Validator : private DPL::Noncopyable +{ + public: + explicit Validator(JSContextRef context, + JSValueRef* exception = NULL); + virtual ~Validator(); + + /** + * Checks if arg is a Date. + * @param arg JSValueRef to check. + * @return true when object is a date, false otherwise + */ + bool isDate(const JSValueRef& arg); + + /** + * Checks if arg is a callback function. + * @param arg JSValueRef to check. + * @return true when object is a callback function, false otherwise + */ + bool isCallback(const JSValueRef& arg); + + /** + * Checks if arg have allowed properties. + * @param allowed allowed property names. + * @param arg JSValueRef to check. + * @return true when object's properties are subset of allowed + */ + bool checkArrayKeys(const std::vector &allowed, + JSValueRef argument); + + bool isNullOrUndefined(const JSValueRef& arg); + + protected: + JSContextRef m_context; + JSValueRef* m_exception; +}; + +template +class ValidatorFactory : private DPL::Noncopyable +{ + public: + /** + * Validator type which deletes itself when gets out of scope. + */ + typedef DPL::SharedPtr ValidatorType; + + public: + /** + * Gets converter object. + * @param context JavaScript context the conversion will be performed in. + * @param[out] exception JavaScript value for storing exception. + * @return Converter object. + */ + static ValidatorType getValidator(JSContextRef context, + JSValueRef* exception = NULL) + { + C* convert = new C(context, exception); + return ValidatorType(convert); + } + + private: + ValidatorFactory(); +}; + +typedef ValidatorFactory BasicValidatorFactory; +typedef BasicValidatorFactory::ValidatorType BasicValidator; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* _VALIDATOR_H_ */ diff --git a/src_mobile/DESCRIPTION b/src_mobile/DESCRIPTION new file mode 100644 index 0000000..bc2b1d7 --- /dev/null +++ b/src_mobile/DESCRIPTION @@ -0,0 +1 @@ +Main source folder diff --git a/src_mobile/dispatch-event/CMakeLists.txt b/src_mobile/dispatch-event/CMakeLists.txt new file mode 100644 index 0000000..3ba4072 --- /dev/null +++ b/src_mobile/dispatch-event/CMakeLists.txt @@ -0,0 +1,59 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Tae-Jeong Lee (taejeong.lee@samsung.com) +# @version 1.0 +# + +pkg_search_module(webkit2 REQUIRED ewebkit2) +pkg_search_module(dpl REQUIRED dpl-efl) + +SET(TARGET_NAME wrt-dispatch-event) + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/dispatch_event_support.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${webkit2_INCLUDE_DIRS} + ${dpl_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${webkit2_LIBRARIES} + ${dpl_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} + DESTINATION ${DESTINATION_LIB_PREFIX} + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES dispatch_event_support.h DESTINATION include/wrt-dispatch-event) \ No newline at end of file diff --git a/src_mobile/dispatch-event/dispatch_event_support.cpp b/src_mobile/dispatch-event/dispatch_event_support.cpp new file mode 100755 index 0000000..7d001a2 --- /dev/null +++ b/src_mobile/dispatch-event/dispatch_event_support.cpp @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file dispatch_event_support.cpp + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _DISPATCH_EVENT_SUPPORT_CPP_ +#define _DISPATCH_EVENT_SUPPORT_CPP_ + +#include "dispatch_event_support.h" + +namespace DispatchEventSupport { + +static std::string getExceptionString(JSContextRef context, JSValueRef exception) +{ + if (exception) + { + JSStringRef jsString = JSValueToStringCopy(context, exception, NULL); + size_t bufSize = JSStringGetMaximumUTF8CStringSize(jsString); + + char* buf = new char[bufSize]; + JSStringGetUTF8CString(jsString, buf, bufSize); + JSStringRelease(jsString); + + std::string ret = buf; + delete[] buf; + + return ret; + } + else + { + return "NULL"; + } +} + +void dispatchAppServiceEvent(JSContextRef context, const float scale, const std::string bundle) +{ + LogDebug("DispatchTizenServiceEvent(" << context << ", " << scale << ", " << bundle << ")"); + + if (context != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"appservice\", true, true);\n" + << "__event.scale = " << scale << ";\n" + << "__event.__bundle = \"" << bundle << "\";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + LogDebug("JSEvaluateScript() - ret:" << ret << ", exception:" << exception << " (" << getExceptionString(context, exception) << ")"); + } +} + +void dispatchSoftKeyboardChangeEvent(JSContextRef context, const std::string state, const int width, const int height) +{ + LogDebug("dispatchSoftKeyboardChangeEvent(" << context << ", " << state << ", " << width << ", " << height << ")"); + + if (context != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"softkeyboardchange\", true, true);\n" + << "__event.state = \"" << state << "\";\n" + << "__event.width = " << width << ";\n" + << "__event.height = " << height << ";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + LogDebug("JSEvaluateScript() - ret:" << ret << ", exception:" << exception << " (" << getExceptionString(context, exception) << ")"); + } +} + +void dispatchStorageEvent(JSContextRef context, + const DPL::Optional& key, + const DPL::Optional& oldValue, + const DPL::Optional& newValue, + const std::string& url) +{ + LogDebug("dispatchStorageEvent(" << + context << ", " << + (key.IsNull() ? "null" : *key) << ", " << + (oldValue.IsNull() ? "null" : *oldValue) << ", " << + (newValue.IsNull() ? "null" : *newValue) << ", " << + url << ")"); + + if (context != NULL) + { + std::stringstream script; + + auto toJSValue = + [](const DPL::Optional& value) -> std::string + { + return (value.IsNull() ? "null" : "\"" + *value + "\""); + }; + + script << "var __event = document.createEvent(\"CustomEvent\");" + << "__event.initCustomEvent(\"storage\", true, true);" + << "__event.key = " << toJSValue(key) << ";" + << "__event.oldValue = " << toJSValue(oldValue) << ";" + << "__event.newValue = " << toJSValue(newValue) << ";" + << "__event.url = \"" << url << "\";" + << "__event.storageArea = widget.preferences;" + << "document.dispatchEvent(__event);" + << "for (var i=0; i < window.frames.length; i++)" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + + // just for debugging + // LogDebug("script :\n" << script.str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + LogDebug("JSEvaluateScript() - ret:" << ret << ", exception:" << exception << " (" << getExceptionString(context, exception) << ")"); + } +} + +void dispatchHwKeyEvent(Evas_Object* ewkView, const std::string key) +{ + LogDebug("dispatchHwKeyEvent(" << ewkView << ", " << key << ")"); + + if (ewkView != NULL && !key.empty()) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"tizenhwkey\", true, true);\n" + << "__event.keyName = \"" << key << "\";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + if (ewk_view_script_execute(ewkView, script.str().c_str(), NULL, NULL) != EINA_TRUE) + { + LogWarning("ewk_view_script_execute returned FALSE!"); + } + } +} + +} +#endif //_DISPATCH_EVENT_SUPPORT_CPP_ diff --git a/src_mobile/dispatch-event/dispatch_event_support.h b/src_mobile/dispatch-event/dispatch_event_support.h new file mode 100644 index 0000000..8a42e20 --- /dev/null +++ b/src_mobile/dispatch-event/dispatch_event_support.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file dispatch_event_support.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _DISPATCH_EVENT_SUPPORT_H_ +#define _DISPATCH_EVENT_SUPPORT_H_ + +#include +#include +#include +#include +#include + +namespace DispatchEventSupport { + +void dispatchAppServiceEvent(JSContextRef context, const float scale, const std::string bundle); +void dispatchSoftKeyboardChangeEvent(JSContextRef context, const std::string state, const int width, const int height); +void dispatchStorageEvent(JSContextRef context, + const DPL::Optional& key, + const DPL::Optional& oldValue, + const DPL::Optional& newValue, + const std::string& url); +void dispatchHwKeyEvent(Evas_Object* ewkView, const std::string key); +} +#endif //_DISPATCH_EVENT_SUPPORT_H_ diff --git a/src_mobile/js-overlay/CMakeLists.txt b/src_mobile/js-overlay/CMakeLists.txt new file mode 100644 index 0000000..f42c3f0 --- /dev/null +++ b/src_mobile/js-overlay/CMakeLists.txt @@ -0,0 +1,67 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 1.0 +# +MACRO(INSTALL_HEADER_FILE HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_JS_OVERLAY}) +ENDMACRO() + +pkg_search_module(webkit2 REQUIRED ewebkit2) +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) + +SET(TARGET_NAME ${TARGET_JS_OVERLAY}) + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/js_function_manager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/js_overlay_functions.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/JSClass + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${webkit2_LIBRARIES} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} + DESTINATION ${DESTINATION_LIB_PREFIX} + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL_HEADER_FILE(js_overlay_types.h) + diff --git a/src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp b/src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp new file mode 100644 index 0000000..7bd26e2 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSSoftKeyboardChangeEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + */ + +#include "JSSoftKeyboardChangeEvent.h" +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::SoftKeyboardChangeEvent::Api; + +#define WIDGET_PLUGIN_NAME "SoftKeyboardChangeEvent" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_STATE "state" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_WIDTH "width" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_HEIGHT "height" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace Tizen { +JSClassDefinition JSSoftKeyboardChangeEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSSoftKeyboardChangeEvent::m_property[] = { + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_STATE, + JSSoftKeyboardChangeEvent::getState, + 0, kJSPropertyAttributeReadOnly }, + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_WIDTH, + JSSoftKeyboardChangeEvent::getWidth, + 0, kJSPropertyAttributeReadOnly }, + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_HEIGHT, + JSSoftKeyboardChangeEvent::getHeight, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSSoftKeyboardChangeEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSoftKeyboardChangeEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSSoftKeyboardChangeEvent::m_jsClassRef = JSClassCreate( + JSSoftKeyboardChangeEvent::getClassInfo()); + +void JSSoftKeyboardChangeEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + LogDebug("entered"); + + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + Assert(priv && "Missing private object"); +} + +void JSSoftKeyboardChangeEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + delete priv; + LogDebug("private object is realised"); +} + +JSValueRef JSSoftKeyboardChangeEvent::getState( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered!"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getState()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSSoftKeyboardChangeEvent::getWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered!"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getWidth()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSSoftKeyboardChangeEvent::getHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getHeight()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +ISoftKeyboardChangeEventPtr JSSoftKeyboardChangeEvent::getPrivateObject( + JSObjectRef arg) +{ + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +} +} diff --git a/src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h b/src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h new file mode 100644 index 0000000..49da22f --- /dev/null +++ b/src_mobile/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSSoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H +#define WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H + +#include +#include +#include + +namespace WrtPlugins { +namespace Tizen { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::SoftKeyboardChangeEvent::Api::ISoftKeyboardChangeEventPtr>:: + Type +JSSoftKeyboardChangeEventPrivateObject; + +class JSSoftKeyboardChangeEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getState( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::SoftKeyboardChangeEvent::Api:: + ISoftKeyboardChangeEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // Tizen +} // WrtPlugins + +#endif // WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H diff --git a/src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.cpp b/src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.cpp new file mode 100644 index 0000000..489656e --- /dev/null +++ b/src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSStorageEvent.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + */ + +#include "JSStorageEvent.h" +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::StorageEvent::Api; + +#define WIDGET_PLUGIN_NAME "StorageEvent" + +#define WRT_STORAGE_EVENT_PROPERTY_KEY "key" +#define WRT_STORAGE_EVENT_PROPERTY_OLD_VALUE "oldValue" +#define WRT_STORAGE_EVENT_PROPERTY_NEW_VALUE "newValue" +#define WRT_STORAGE_EVENT_PROPERTY_URL "url" +#define WRT_STORAGE_EVENT_PROPERTY_STORAGE_AREA "storageArea" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + LogError("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace W3C { +JSClassDefinition JSStorageEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSStorageEvent::m_property[] = { + { WRT_STORAGE_EVENT_PROPERTY_KEY, JSStorageEvent::getKey, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_OLD_VALUE, JSStorageEvent::getOldValue, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_NEW_VALUE, JSStorageEvent::getNewValue, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_URL, JSStorageEvent::getUrl, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_STORAGE_AREA, JSStorageEvent::getStorageArea, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSStorageEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSStorageEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSStorageEvent::m_jsClassRef = JSClassCreate( + JSStorageEvent::getClassInfo()); + +void JSStorageEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + LogDebug("entered"); + + JSStorageEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + Assert(priv && "Missing private object"); +} + +void JSStorageEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSStorageEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + delete priv; + LogDebug("private object is realised"); +} + +JSValueRef JSStorageEvent::getKey( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + return converter.toJSValueRef(getPrivateObject(object)->getKey()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getOldValue( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + DPL::OptionalString oldValue = getPrivateObject(object)->getOldValue(); + + if (!oldValue) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(DPL::ToUTF8String(*oldValue)); + } + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getNewValue( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + DPL::OptionalString newValue = getPrivateObject(object)->getNewValue(); + + if (!newValue) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(DPL::ToUTF8String(*newValue)); + } + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getUrl( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + return converter.toJSValueRef(getPrivateObject(object)->getUrl()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR +} + +JSValueRef JSStorageEvent::getStorageArea( + JSContextRef context, + JSObjectRef /*object*/, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + LogError("Not implemented"); + return JSValueMakeUndefined(context); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +IStorageEventPtr JSStorageEvent::getPrivateObject(JSObjectRef arg) +{ + JSStorageEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +} +} diff --git a/src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.h b/src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.h new file mode 100644 index 0000000..0460f39 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/JSClass/JSStorageEvent.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSStorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_STORAGE_EVENT_H_ +#define _WRT_PLUGIN_JS_STORAGE_EVENT_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::StorageEvent::Api::IStorageEventPtr>::Type +JSStorageEventPrivateObject; + +class JSStorageEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getKey( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getOldValue( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getNewValue( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getUrl( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getStorageArea( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::StorageEvent::Api::IStorageEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // W3C +} // WrtPlugins + +#endif // _WRT_PLUGIN_JS_STORAGE_EVENT_H_ diff --git a/src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp b/src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp new file mode 100644 index 0000000..516d189 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSTizenServiceEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + */ + +#include "JSTizenServiceEvent.h" +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::TizenServiceEvent::Api; + +#define WIDGET_PLUGIN_NAME "TizenServiceEvent" + +#define TIZEN_SERVICE_EVENT_PROPERTY_SCALE "scale" +#define TIZEN_SERVICE_EVENT_PROPERTY_BUNDLE "__bundle" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + LogError("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace Tizen { +JSClassDefinition JSTizenServiceEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSTizenServiceEvent::m_property[] = { + { TIZEN_SERVICE_EVENT_PROPERTY_SCALE, JSTizenServiceEvent::getScale, + 0, kJSPropertyAttributeReadOnly }, + { TIZEN_SERVICE_EVENT_PROPERTY_BUNDLE, JSTizenServiceEvent::getBundle, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSTizenServiceEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTizenServiceEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTizenServiceEvent::m_jsClassRef = JSClassCreate( + JSTizenServiceEvent::getClassInfo()); + +void JSTizenServiceEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + LogDebug("entered"); + + JSTizenServiceEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + Assert(priv && "Missing private object"); +} + +void JSTizenServiceEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSTizenServiceEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + delete priv; + LogDebug("private object is realised"); +} + +JSValueRef JSTizenServiceEvent::getScale( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getScale()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSTizenServiceEvent::getBundle( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getBundle()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +ITizenServiceEventPtr JSTizenServiceEvent::getPrivateObject(JSObjectRef arg) +{ + JSTizenServiceEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +} +} diff --git a/src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h b/src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h new file mode 100644 index 0000000..a079dc5 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSTizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ +#define _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace Tizen { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::TizenServiceEvent::Api::ITizenServiceEventPtr>::Type +JSTizenServiceEventPrivateObject; + +class JSTizenServiceEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getScale( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getBundle( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::TizenServiceEvent::Api::ITizenServiceEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // Tizen +} // WrtPlugins + +#endif // _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ diff --git a/src_mobile/js-overlay/deprecated/js_iframe_support.cpp b/src_mobile/js-overlay/deprecated/js_iframe_support.cpp new file mode 100755 index 0000000..904d4e1 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/js_iframe_support.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file IFrameSupport.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +IFrameSupport::IFramesContainer IFrameSupport::m_iframesObject = + IFrameSupport::IFramesContainer(); + +void IFrameSupport::RegisterWidget(java_script_context_t /*global_context*/, + js_object_instance_t iframe, + js_object_instance_t object) +{ + LogDebug("New widget instance registered"); + LogDebug("iframe: " << iframe); + LogDebug("object: " << object); + getIFrameData(static_cast(iframe))->widget = + static_cast(object); +} + +void IFrameSupport::RegisterAddEventListener( + java_script_context_t /*global_context*/, + js_object_instance_t iframe, + js_object_instance_t object) +{ + LogDebug("New addEventListener instance registered"); + LogDebug("iframe: " << iframe); + LogDebug("object: " << object); + getIFrameData(static_cast(iframe))->addEventListener + = static_cast(object); +} + +JSObjectRef IFrameSupport::getIFrameObjectForWidget(JSObjectRef widgetObject) +{ + FOREACH(it, m_iframesObject) + { + if (it->second->widget == widgetObject) { + LogDebug("iframe found"); + return it->first; + } + } + LogDebug("Iframe not found"); + return NULL; +} + +IFrameDataPtr IFrameSupport::getIFrameData(JSObjectRef iframe) +{ + auto it = m_iframesObject.find(iframe); + if (it != m_iframesObject.end()) { + return it->second; + } + + return m_iframesObject[iframe] = IFrameDataPtr(new IFrameData()); +} +} +} diff --git a/src_mobile/js-overlay/deprecated/js_iframe_support.h b/src_mobile/js-overlay/deprecated/js_iframe_support.h new file mode 100755 index 0000000..de07932 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/js_iframe_support.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file IFrameSupport.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_SRC_W3C_WIDGET_IFRAME_SUPPORT_H_ +#define _WRT_PLUGINS_SRC_W3C_WIDGET_IFRAME_SUPPORT_H_ + +#include +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +struct IFrameData +{ + IFrameData() : widget(0), addEventListener(0){} + + JSObjectRef widget; + JSObjectRef addEventListener; +}; +typedef std::shared_ptr IFrameDataPtr; + +class IFrameSupport +{ + public: + static void RegisterWidget(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); + + static void RegisterAddEventListener(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); + + static JSObjectRef getIFrameObjectForWidget(JSObjectRef widgetObject); + + private: + //map iframe:objects + typedef std::map IFramesContainer; + + static IFramesContainer m_iframesObject; + + private: + static IFrameDataPtr getIFrameData(JSObjectRef iframe); +}; +} +} + +#endif diff --git a/src_mobile/js-overlay/deprecated/js_overlay_addEventListener.cpp b/src_mobile/js-overlay/deprecated/js_overlay_addEventListener.cpp new file mode 100755 index 0000000..8cb6801 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/js_overlay_addEventListener.cpp @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file AddEventListenerSupport.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { + +const std::string storageEventName = "storage"; +const std::string appServiceEventName = "appservice"; +const std::string softKeyboardChangeEventName = "softkeyboardchange"; + +AddEventListenerSupport::IFramesListeners +AddEventListenerSupport::m_listeners = + AddEventListenerSupport::IFramesListeners(); + +JSValueRef AddEventListenerSupport::AddEventListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* /*exception*/) +{ + LogDebug("Add event listener invoked"); + LogDebug("This(iframe?):" << thisObject); + LogDebug("object:" << object); + + JSContextRef global_context = JSContextGetGlobalContext(context); + LogDebug("context:" << context << "(global:" << global_context << ")"); + + if (argumentCount < 2 || !JSValueIsString(context, arguments[0])) { + LogError("Wrong arguments"); + return JSValueMakeUndefined(context); + } + + std::string eventName = WrtDeviceApis::CommonsJavaScript:: + Converter(context).toString(arguments[0]); + LogDebug("Event name: " << eventName); + + if (eventName != storageEventName && + eventName != appServiceEventName && + eventName != softKeyboardChangeEventName) + { + LogDebug("Event type not supported"); + return JSValueMakeUndefined(context); + } + + JSObjectRef objectCb = JSValueToObject(context, arguments[1], NULL); + if (!JSObjectIsFunction(context, objectCb)) { + LogError("JS object is not a function"); + return JSValueMakeUndefined(context); + } + JSValueProtect(global_context, arguments[1]); + //add object to Listeners + //set event information according to each event type + CallbackData data; + data.object = objectCb; + data.thisObject = thisObject; + data.context = global_context; + + if (eventName == storageEventName) { + data.eventType = StorageCustomEvent; + } else if (eventName == appServiceEventName) { + data.eventType = ServiceCustomEvent; + } else if (eventName == softKeyboardChangeEventName) { + data.eventType = SoftKeyboardChangeCustomEvent; + } + + getIFrameListeners(thisObject)->push_back(data); + + return JSValueMakeUndefined(context); +} + +void AddEventListenerSupport::RemoveIFrame(JSObjectPtr iframe) +{ + auto it = m_listeners.find(iframe->getObject()); + if (it == m_listeners.end()) { + LogWarning("Iframe not registered"); + return; + } + + FOREACH(listener, *it->second) + { + JSValueUnprotect(listener->context, listener->object); + } + m_listeners.erase(it); + LogDebug("Iframe removed from add event listener object"); +} + +void AddEventListenerSupport::CallStorageListenersFromDifferentIFrames( + JSObjectRef iframe, + const WrtDeviceApis::StorageEvent::Api::IStorageEventPtr& event) +{ + LogDebug("Invoked callbacks"); + + FOREACH(it, m_listeners) + { + if (it->first == iframe) { + continue; + } + + FOREACH(listener, *it->second) + { + LogDebug("Call"); + + auto eventPriv = + new JSStorageEventPrivateObject(listener->context, event); + + JSObjectRef eventObject = + JSObjectMake(listener->context, JSStorageEvent::getClassRef(), eventPriv); + const size_t argc = 1; + JSValueRef argv[argc] = { eventObject }; + + JSValueProtect(listener->context, eventObject); + + if (listener->eventType == StorageCustomEvent) + { + JSObjectCallAsFunction( + listener->context, + listener->object, + NULL, + argc, + argv, + NULL); + } + + JSValueUnprotect(listener->context, eventObject); + } + } + + LogDebug("Done"); +} + +void AddEventListenerSupport::CallCustomEventListenersFromIFrame( + JSObjectRef iframe, + CustomEventType eventType, + JSObjectRef eventObject) +{ + LogDebug("Invoked callbacks"); + + IFramesListeners::iterator it = m_listeners.find(iframe); + if (it == m_listeners.end()) { + LogDebug("This frame object not existed"); + return; + } + + const size_t argc = 1; + JSValueRef argv[argc] = { eventObject }; + + FOREACH(listener, *it->second) + { + if (listener->eventType == eventType) { + LogDebug("Call"); + JSObjectCallAsFunction( + listener->context, + listener->object, + iframe, + argc, + argv, + NULL); + } + } + LogDebug("Done"); +} + +AddEventListenerSupport::ListenersPtr +AddEventListenerSupport::getIFrameListeners(JSObjectRef iframe) +{ + auto it = m_listeners.find(iframe); + if (it != m_listeners.end()) { + return it->second; + } + + return m_listeners[iframe] = ListenersPtr(new Listeners()); +} +} +} diff --git a/src_mobile/js-overlay/deprecated/js_overlay_addEventListener.h b/src_mobile/js-overlay/deprecated/js_overlay_addEventListener.h new file mode 100755 index 0000000..0a9717e --- /dev/null +++ b/src_mobile/js-overlay/deprecated/js_overlay_addEventListener.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file js_overlay_addEventListener.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_SRC_W3C_WIDGET_ADDEVENTLISTENERSUPPORT_H_ +#define _WRT_PLUGINS_SRC_W3C_WIDGET_ADDEVENTLISTENERSUPPORT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// import temporarily from JSContextRefPrivate.h +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +namespace WrtPlugins { +namespace W3C { +class AddEventListenerSupport +{ + public: + static JSValueRef AddEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static void RemoveIFrame(JSObjectPtr iframe); + + static void CallStorageListenersFromDifferentIFrames( + JSObjectRef iframe, + const WrtDeviceApis::StorageEvent::Api::IStorageEventPtr& event); + + static void CallCustomEventListenersFromIFrame( + JSObjectRef iframe, + CustomEventType eventType, + JSObjectRef eventObject); + + private: + + struct CallbackData { + CustomEventType eventType; + JSObjectRef object; + JSObjectRef thisObject; + JSContextRef context; + }; + + typedef std::list Listeners; + typedef std::shared_ptr ListenersPtr; + + //first-iframe, 2nd - listeners list + typedef std::map IFramesListeners; + + static IFramesListeners m_listeners; + + private: + static ListenersPtr getIFrameListeners(JSObjectRef iframe); +}; +} +} + +#endif diff --git a/src_mobile/js-overlay/deprecated/js_overlay_support.cpp b/src_mobile/js-overlay/deprecated/js_overlay_support.cpp new file mode 100644 index 0000000..cad75a5 --- /dev/null +++ b/src_mobile/js-overlay/deprecated/js_overlay_support.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_overlay_support.cpp + * @author + * @version 1.0 + * @brief + */ +#include +#include +#include +#include + +#include + +namespace JSOverlaySupport { +class JSFunctionDispatcher +{ + public: + struct PrivateData + { + //required to unprotect object in destructor; + JSContextRef context; + JSObjectPtr originalFunction; + JSObjectPtr overlayFunction; + }; + + static JSClassRef getClassRef(); + + private: + static JSClassDefinition m_classInfo; + + private: + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef callAsFunction(JSContextRef ctx, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +JSObjectPtr createWrappedFunction( + JSGlobalContextRef ctx, + const JSObjectPtr& originalFunction, + const JSObjectPtr& overlayFunction, + const std::string& name) +{ + LogDebug("Creation overlay for function: " << name); + JSStringRef name_js = JSStringCreateWithUTF8CString(name.c_str()); + + JSFunctionDispatcher::PrivateData* priv = + new JSFunctionDispatcher::PrivateData; + priv->context = ctx; + priv->overlayFunction = overlayFunction; + priv->originalFunction = originalFunction; + + auto fun = JSObjectMake(ctx, JSFunctionDispatcher::getClassRef(), priv); + + JSStringRelease(name_js); + + LogDebug("JSValueProtect invoked for: " + << overlayFunction->getObject() << " " + << originalFunction->getObject() << " Wrapper:" + << fun); + + //the value is unprotected in finalize of the JSFunctionDispatcher object + JSValueProtect(ctx, + static_cast( + overlayFunction->getObject())); + + return JSObjectPtr(new JSObject(fun)); +} + +JSClassDefinition JSFunctionDispatcher::m_classInfo = { + 0, + kJSClassAttributeNone, + "IGNORED", + 0, + 0, + 0, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + callAsFunction, + NULL, + NULL, + NULL +}; + +JSClassRef JSFunctionDispatcher::getClassRef() +{ + static auto classRef = JSClassCreate(&m_classInfo); + return classRef; +} + +void JSFunctionDispatcher::initialize(JSContextRef /*context*/, + JSObjectRef /*object*/) +{ + LogDebug("Initialize"); +} + +void JSFunctionDispatcher::finalize(JSObjectRef object) +{ + LogDebug("finalize"); + + PrivateData* priv = static_cast(JSObjectGetPrivate(object)); + if (priv) { + JSValueUnprotect(priv->context, + static_cast( + priv->overlayFunction->getObject())); + delete priv; + } +} + +JSValueRef JSFunctionDispatcher::callAsFunction( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Dispatcher invoked"); + + JSValueRef result = JSValueMakeUndefined(context); + + JSFunctionDispatcher::PrivateData* priv = + static_cast + (JSObjectGetPrivate(object)); + + if (!priv) { + LogError("Private object is NULL"); + return result; + } + + //call overlayed function + if (priv->overlayFunction->getObject()) { + LogDebug("Overlayed function will be invoked..."); + result = JSObjectCallAsFunction( + priv->context, + static_cast( + priv->overlayFunction->getObject()), + thisObject, + argumentCount, + arguments, + exception); + } + + //call original function + if (priv->originalFunction->getObject()) { + LogDebug("Original function will be invoked.."); + result = JSObjectCallAsFunction( + context, + static_cast( + priv->originalFunction->getObject()), + thisObject, + argumentCount, + arguments, + exception); + } + + LogDebug("Done"); + return result; +} +} diff --git a/src_mobile/js-overlay/deprecated/js_overlay_support.h b/src_mobile/js-overlay/deprecated/js_overlay_support.h new file mode 100644 index 0000000..0cfb19b --- /dev/null +++ b/src_mobile/js-overlay/deprecated/js_overlay_support.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_function_wrapper.h + * @author + * @version 1.0 + * @brief + */ + +#ifndef _JAVASCRIPT_OVERLAY_SUPPORT_H +#define _JAVASCRIPT_OVERLAY_SUPPORT_H + +#include +#include +#include +#include +#include + +namespace JSOverlaySupport { +JSObjectPtr createWrappedFunction( + JSGlobalContextRef ctx, + const JSObjectPtr& originalFunction, + const JSObjectPtr& overlayFunction, + const std::string& name); +} + +#endif diff --git a/src_mobile/js-overlay/js_function_manager.cpp b/src_mobile/js-overlay/js_function_manager.cpp new file mode 100644 index 0000000..dab34b9 --- /dev/null +++ b/src_mobile/js-overlay/js_function_manager.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_function_manager.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @author Yunchan Cho (yunchan.cho@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include +#include +#include + +IMPLEMENT_SAFE_SINGLETON(JsFunctionManager) + +namespace { +const char* JSPRINT_NAME = "jsPrint"; +const char* JSGLOBAL_OBJECT = "GLOBAL_OBJECT"; +const char* JSHOOK_NAME = "jsHook"; +} + +namespace JavaScriptFunctions { +//options +class_definition_options_t jsHookfunctionsOptions = { + JS_FUNCTION, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + reinterpret_cast(JSCFunctions::JavaScriptHookProc) +}; + +class_definition_options_t jsPrintfunctionsOptions = { + JS_FUNCTION, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + reinterpret_cast(JSCFunctions::JavaScriptPrintProc) +}; + +js_entity_definition_t jsPrint = { + JSGLOBAL_OBJECT, + JSPRINT_NAME, + "", + NULL, + NULL, + &jsPrintfunctionsOptions +}; + +js_entity_definition_t jsHook = { + JSGLOBAL_OBJECT, + JSHOOK_NAME, + "", + NULL, + NULL, + &jsHookfunctionsOptions +}; + +const js_entity_definition_ptr_t jsPrintPtr = &jsPrint; +const js_entity_definition_ptr_t jsHookPtr = &jsHook; +} + +bool JsFunctionManager::initialize() +{ + _D("JSObjectDeclaration for js functions are intialized"); + JSObjectDeclarationPtr jsPrintObj( + new JSObjectDeclaration(JavaScriptFunctions::jsPrintPtr)); + + JSObjectDeclarationPtr jsHookObj( + new JSObjectDeclaration(JavaScriptFunctions::jsHookPtr)); + + m_functions.push_back(jsPrintObj); + m_functions.push_back(jsHookObj); + + return true; +} + +JsFunctionManager::Functions JsFunctionManager::getFunctions() +{ + _D("get standard js fucntions"); + static bool initialized = initialize(); + (void) initialized; + return m_functions; +} diff --git a/src_mobile/js-overlay/js_function_manager.h b/src_mobile/js-overlay/js_function_manager.h new file mode 100644 index 0000000..d6bd80e --- /dev/null +++ b/src_mobile/js-overlay/js_function_manager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_function_manager.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_FUNCTION_MANGER_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_FUNCTION_MANGER_H_ + +#include +#include +#include + +#include + +class JsFunctionManager : private DPL::Noncopyable +{ + public: + typedef std::list Functions; + + public: + Functions getFunctions(); + + private: + JsFunctionManager() + {} + + bool initialize(); + + private: + Functions m_functions; + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton JsFunctionManagerSingleton; + +#endif + diff --git a/src_mobile/js-overlay/js_overlay_functions.cpp b/src_mobile/js-overlay/js_overlay_functions.cpp new file mode 100644 index 0000000..8097d20 --- /dev/null +++ b/src_mobile/js-overlay/js_overlay_functions.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file javascript_functions.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include + +namespace JSCFunctions { +std::string ConvertJSStringToStdString(JSStringRef value) +{ + int nSize = JSStringGetLength(value) + 1; + DPL::ScopedArray textStr(new char[nSize]); + JSStringGetUTF8CString(value, textStr.Get(), nSize); + std::string ret = textStr.Get(); + return ret; +} + +JSValueRef JavaScriptPrintProc(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + if (argumentCount == 0 || !JSValueIsString(context, arguments[0])) { + LogError("Argument is not string"); + return JSValueMakeUndefined(context); + } + + JSStringRef textRef = JSValueToStringCopy(context, arguments[0], exception); + int nSize = JSStringGetLength(textRef) + 1; + + DPL::ScopedArray textStr(new char[nSize]); + + JSStringGetUTF8CString(textRef, textStr.Get(), nSize); + LogDebug("\033[00;35m[jsPrint] " << textStr.Get()); + + JSStringRelease(textRef); + return JSValueMakeBoolean(context, true); +} + +JSValueRef JavaScriptHookProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + bool inError = false; + if (argumentCount < 2 || + argumentCount > 3 || + !JSValueIsString(context, arguments[0]) || + !JSValueIsString(context, arguments[1])) + { + inError = true; + } + + if (inError) { + LogError("*********************************************"); + LogError("*********************************************"); + LogError("Cannot print test Result"); + LogError("*********************************************"); + LogError("*********************************************"); + return JSValueMakeUndefined(context); + } + + std::string id, result, message; + JSStringRef idRef = JSValueToStringCopy(context, arguments[0], exception); + id = ConvertJSStringToStdString(idRef); + JSStringRelease(idRef); + JSStringRef idResult = JSValueToStringCopy(context, + arguments[1], + exception); + result = ConvertJSStringToStdString(idResult); + JSStringRelease(idResult); + + if (argumentCount == 3 && !JSValueIsString(context, arguments[2])) { + JSStringRef idMessage = JSValueToStringCopy(context, + arguments[0], + exception); + message = ConvertJSStringToStdString(idMessage); + JSStringRelease(idMessage); + } + + LogDebug("\033[00;35m***********************************************"); + LogDebug("\033[00;35m***********************************************"); + LogDebug("\033[00;35m TEST ID: " << id); + LogDebug("\033[00;35m RESULT: " << result); + LogDebug("\033[00;35m MESSAGE: " << message); + LogDebug("\033[00;35m***********************************************"); + LogDebug("\033[00;35m***********************************************"); + + return JSValueMakeBoolean(context, true); +} +} diff --git a/src_mobile/js-overlay/js_overlay_functions.h b/src_mobile/js-overlay/js_overlay_functions.h new file mode 100644 index 0000000..3c7f86a --- /dev/null +++ b/src_mobile/js-overlay/js_overlay_functions.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file javascript_functions.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_EFL_JAVASCRIPT_FUNCTIONS_H_ +#define WRT_SRC_PLUGIN_SERVICE_EFL_JAVASCRIPT_FUNCTIONS_H_ + +#include + +namespace JSCFunctions { +JSValueRef JavaScriptPrintProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); +JSValueRef JavaScriptHookProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); +} + +#endif + diff --git a/src_mobile/js-overlay/js_overlay_types.h b/src_mobile/js-overlay/js_overlay_types.h new file mode 100644 index 0000000..e47634f --- /dev/null +++ b/src_mobile/js-overlay/js_overlay_types.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file js_overlay_types.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ +#define _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ + +#include + +namespace WrtPlugins { +namespace W3C { +// If needed, enum for new custom event should be defined here +enum CustomEventType { + StorageCustomEvent, + ServiceCustomEvent, + SoftKeyboardChangeCustomEvent, +}; + +// Argument structure of SoftKeyboardChangeCustomEvent +typedef struct SoftKeyboardChangeArgs { + std::string state; // value is 'on' or 'off' + int width; + int height; + SoftKeyboardChangeArgs() : + width(0), + height(0) + {} +} SoftKeyboardChangeArgs; + +// If needed, argument structure of other custom events should be defined here +} // W3C +} // WrtPlugins +#endif // _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ diff --git a/src_mobile/modules/API/CMakeLists.txt b/src_mobile/modules/API/CMakeLists.txt new file mode 100644 index 0000000..1a64e70 --- /dev/null +++ b/src_mobile/modules/API/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include_config_file(Filesystem) +include_config_file(Widget) +include_config_file(LocalStorage) +include_config_file(WidgetDB) +include_config_file(PluginManager) +include_config_file(StorageEvent) +include_config_file(TizenServiceEvent) +include_config_file(SoftKeyboardChangeEvent) diff --git a/src_mobile/modules/API/DESCRIPTION b/src_mobile/modules/API/DESCRIPTION new file mode 100644 index 0000000..76eb35c --- /dev/null +++ b/src_mobile/modules/API/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Platform independent platform API diff --git a/src_mobile/modules/API/Filesystem/Enums.h b/src_mobile/modules/API/Filesystem/Enums.h new file mode 100644 index 0000000..81e7d0d --- /dev/null +++ b/src_mobile/modules/API/Filesystem/Enums.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_ENUMS_H_ +#define WRTDEVICEAPIS_FILESYSTEM_ENUMS_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +enum LocationType +{ + LT_APPS, + LT_DOCUMENTS, + LT_DOWNLOADS, + LT_GAMES, + LT_IMAGES, + LT_OTHERS, + LT_ROOT, + LT_SDCARD, + LT_SOUNDS, + LT_TEMP, + LT_VIDEOS +}; + +enum NodeType +{ + NT_DIRECTORY, + NT_FILE +}; + +enum AccessMode +{ + AM_READ = 0x0001, + AM_WRITE = 0x0002, + AM_APPEND = 0x0004 +}; + +/** + * Used in @see IManager::access(). + */ +enum AccessType +{ + 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 + AT_EXISTS = 0x0008 //!< AT_EXISTS - checks for existence +}; + +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 FiltersMap; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_ENUMS_H_ */ diff --git a/src_mobile/modules/API/Filesystem/EventCopy.cpp b/src_mobile/modules/API/Filesystem/EventCopy.cpp new file mode 100644 index 0000000..cd4efa1 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventCopy.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventCopy.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventCopy::EventCopy(const IPathPtr& src, + const IPathPtr& dest) : + m_src(src), + m_dest(dest), + m_options(OPT_NONE) +{ + Assert(src && "Source path not set."); + Assert(dest && "Destination path not set."); +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventCopy.h b/src_mobile/modules/API/Filesystem/EventCopy.h new file mode 100644 index 0000000..62bef44 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventCopy.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTCOPY_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTCOPY_H_ + +#include +#include +#include "IPath.h" +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventCopy : public Commons::IEvent +{ + 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 + // WrtDeviceApis::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr EventCopyPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTCOPY_H_ diff --git a/src_mobile/modules/API/Filesystem/EventFind.cpp b/src_mobile/modules/API/Filesystem/EventFind.cpp new file mode 100644 index 0000000..c8c01a9 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventFind.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventFind.h" + +#include +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +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(name, value)); +} + +FiltersMap EventFind::getFilters() const +{ + return m_filters; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventFind.h b/src_mobile/modules/API/Filesystem/EventFind.h new file mode 100644 index 0000000..47d6e50 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventFind.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_IEVENTFILESYSTEMFIND_H_ +#define WRTDEVICEAPIS_IEVENTFILESYSTEMFIND_H_ + +#include +#include +#include +#include "IPath.h" +#include "INodeTypes.h" +#include "Enums.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventFind : public Commons::IEvent +{ + 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 EventFindPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_IEVENTFILESYSTEMFIND_H_ diff --git a/src_mobile/modules/API/Filesystem/EventListNodes.cpp b/src_mobile/modules/API/Filesystem/EventListNodes.cpp new file mode 100644 index 0000000..3fed54f --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventListNodes.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventListNodes.h" +#include +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventListNodes::EventListNodes(const INodePtr& node) : m_node(node) +{ + Assert(m_node && "Node can't be NULL."); +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventListNodes.h b/src_mobile/modules/API/Filesystem/EventListNodes.h new file mode 100644 index 0000000..a856546 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventListNodes.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTLISTNODES_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTLISTNODES_H_ + +#include +#include +#include "INodeTypes.h" +#include "NodeFilter.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventListNodes : public Commons::IEvent +{ + 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 EventListNodesPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTLISTNODES_H_ diff --git a/src_mobile/modules/API/Filesystem/EventMove.cpp b/src_mobile/modules/API/Filesystem/EventMove.cpp new file mode 100644 index 0000000..0164856 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventMove.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventMove.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventMove::EventMove(const IPathPtr& src, + const IPathPtr& dest) : + m_src(src), + m_dest(dest), + m_options(OPT_NONE) +{ + Assert(src && "Source path not set."); + Assert(dest && "Destination path not set."); +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventMove.h b/src_mobile/modules/API/Filesystem/EventMove.h new file mode 100644 index 0000000..d9716f0 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventMove.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTMOVE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTMOVE_H_ + +#include +#include +#include "IPath.h" +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventMove : public Commons::IEvent +{ + 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 + // WrtDeviceApis::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr EventMovePtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTMOVE_H_ diff --git a/src_mobile/modules/API/Filesystem/EventOpen.cpp b/src_mobile/modules/API/Filesystem/EventOpen.cpp new file mode 100644 index 0000000..274e963 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventOpen.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventOpen.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventOpen.h b/src_mobile/modules/API/Filesystem/EventOpen.h new file mode 100644 index 0000000..5ab5662 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventOpen.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTOPEN_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTOPEN_H_ + +#include +#include +#include "IStream.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventOpen : public Commons::IEvent +{ + 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); + + private: + int m_mode; ///< Mode. + IStreamPtr m_stream; ///< Opened stream. +}; + +typedef DPL::SharedPtr EventOpenPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTOPEN_H_ diff --git a/src_mobile/modules/API/Filesystem/EventReadText.cpp b/src_mobile/modules/API/Filesystem/EventReadText.cpp new file mode 100644 index 0000000..560687e --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventReadText.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventReadText.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +std::string EventReadText::getResult() const +{ + return m_result; +} + +void EventReadText::setResult(const std::string& result) +{ + m_result = result; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventReadText.h b/src_mobile/modules/API/Filesystem/EventReadText.h new file mode 100644 index 0000000..986b565 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventReadText.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTREADTEXT_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTREADTEXT_H_ + +#include +#include +#include +#include "IPath.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventReadText : public Commons::IEvent +{ + public: + /** + * Gets read text. + * @return Text. + */ + std::string getResult() const; + + /** + * Sets read text. + * @param result Text. + */ + void setResult(const std::string& result); + + private: + std::string m_result; ///< Read text. +}; + +typedef DPL::SharedPtr EventReadTextPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTREADTEXT_H_ diff --git a/src_mobile/modules/API/Filesystem/EventRemove.cpp b/src_mobile/modules/API/Filesystem/EventRemove.cpp new file mode 100644 index 0000000..6be8f41 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventRemove.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventRemove.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventRemove::EventRemove(const IPathPtr& path) : + m_path(path), + m_options(OPT_NONE) +{ + Assert(m_path && "Path is not set."); +} + +IPathPtr EventRemove::getPath() const +{ + return m_path; +} + +int EventRemove::getOptions() const +{ + return m_options; +} + +void EventRemove::setOptions(int options) +{ + m_options = options; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventRemove.h b/src_mobile/modules/API/Filesystem/EventRemove.h new file mode 100644 index 0000000..be3aecd --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventRemove.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTREMOVE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTREMOVE_H_ + +#include +#include +#include "INode.h" +#include "Enums.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventRemove : public Commons::IEvent +{ + 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 + // WrtDeviceApis::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr EventRemovePtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTREMOVE_H_ diff --git a/src_mobile/modules/API/Filesystem/EventResolve.cpp b/src_mobile/modules/API/Filesystem/EventResolve.cpp new file mode 100644 index 0000000..2473795 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventResolve.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventResolve.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventResolve::EventResolve(const IPathPtr& path) : m_path(path) +{} + +IPathPtr EventResolve::getPath() const +{ + return m_path; +} + +INodePtr EventResolve::getResult() const +{ + return m_node; +} + +void EventResolve::setResult(const INodePtr& node) +{ + m_node = node; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/EventResolve.h b/src_mobile/modules/API/Filesystem/EventResolve.h new file mode 100644 index 0000000..1d50258 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/EventResolve.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTRESOLVE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTRESOLVE_H_ + +#include +#include +#include "IPath.h" +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventResolve : public Commons::IEvent +{ + 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); + + private: + IPathPtr m_path; ///< Path to the requested node. + INodePtr m_node; ///< Resolved node. +}; + +typedef DPL::SharedPtr EventResolvePtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTRESOLVE_H_ diff --git a/src_mobile/modules/API/Filesystem/IManager.cpp b/src_mobile/modules/API/Filesystem/IManager.cpp new file mode 100644 index 0000000..92219f5 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/IManager.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include "IManager.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +IManager& IManager::getInstance() +{ + static Manager instance; + return instance; +} + +bool IManager::fileExists(const std::string &file) +{ + return WrtDeviceApis::Filesystem::Manager::fileExists(file); +} + +IManager::IManager() : + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD) +{} + +IManager::~IManager() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/IManager.h b/src_mobile/modules/API/Filesystem/IManager.h new file mode 100644 index 0000000..bc3cf0d --- /dev/null +++ b/src_mobile/modules/API/Filesystem/IManager.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_IMANAGER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_IMANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +typedef std::vector LocationPaths; +typedef std::vector LocationTypes; + +class IManager : + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver +{ + public: + static IManager& getInstance(); + static bool fileExists(const std::string &file); + + virtual ~IManager() = 0; + + /** + * Gets base path. + * @return Valid path or empty shared pointer. + */ + virtual IPathPtr getBasePath() const = 0; + + /** + * Gets path for specified location type. + * @param type Location type @see + * WrtDeviceApis::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; + + /** + * 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; + + protected: + IManager(); + + virtual void OnRequestReceived(const EventResolvePtr& event) = 0; + virtual void OnRequestReceived(const EventCopyPtr& event) = 0; + virtual void OnRequestReceived(const EventMovePtr& event) = 0; + virtual void OnRequestReceived(const EventRemovePtr& event) = 0; + virtual void OnRequestReceived(const EventFindPtr& event) = 0; +}; // IManager +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_IMANAGER_H_ diff --git a/src_mobile/modules/API/Filesystem/INode.cpp b/src_mobile/modules/API/Filesystem/INode.cpp new file mode 100644 index 0000000..cd30a04 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/INode.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "INode.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +INode::INode() : + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD) +{} + +INode::~INode() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/INode.h b/src_mobile/modules/API/Filesystem/INode.h new file mode 100644 index 0000000..c227aa9 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/INode.h @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_INODE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_INODE_H_ + +#include +#include +#include +#include +#include +#include +#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 WrtDeviceApis { +namespace Filesystem { +namespace Api { +class INode : + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver +{ + public: + typedef std::vector 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 /*DEPREC*/ = 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 std::size_t 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; + + protected: + INode(); +}; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_INODE_H_ */ diff --git a/src_mobile/modules/API/Filesystem/INodeTypes.h b/src_mobile/modules/API/Filesystem/INodeTypes.h new file mode 100644 index 0000000..c1c49f7 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/INodeTypes.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_INODETYPES_H_ +#define WRTDEVICEAPIS_FILESYSTEM_INODETYPES_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class INode; + +typedef DPL::SharedPtr INodePtr; + +typedef std::vector NodeList; +typedef NodeList::iterator NodeListIterator; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_INODETYPES_H_ diff --git a/src_mobile/modules/API/Filesystem/IPath.cpp b/src_mobile/modules/API/Filesystem/IPath.cpp new file mode 100644 index 0000000..de9b32d --- /dev/null +++ b/src_mobile/modules/API/Filesystem/IPath.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "IPath.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +IPathPtr IPath::create(const std::string& str) +{ + return Path::create(str); +} + +IPath::SeparatorType IPath::getSeparator() +{ + return Path::getSeparator(); +} + +IPath::~IPath() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/IPath.h b/src_mobile/modules/API/Filesystem/IPath.h new file mode 100644 index 0000000..3c32abd --- /dev/null +++ b/src_mobile/modules/API/Filesystem/IPath.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_IPATH_H_ +#define WRTDEVICEAPIS_FILESYSTEM_IPATH_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class IPath; +typedef DPL::SharedPtr 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 bool operator==(const IPath& lhs, const IPath& rhs) +{ + return (lhs.getFullPath() == rhs.getFullPath()); +} + +inline bool operator==(const IPath& lhs, const std::string& rhs) +{ + return (lhs.getFullPath() == rhs); +} + +inline bool operator==(const std::string& lhs, const IPath& rhs) +{ + return (lhs == rhs.getFullPath()); +} + +inline bool operator!=(const IPath& lhs, const IPath& rhs) +{ + return (lhs.getFullPath() != rhs.getFullPath()); +} + +inline bool operator!=(const IPath& lhs, const std::string& rhs) +{ + return (lhs.getFullPath() != rhs); +} + +inline bool operator!=(const std::string& lhs, const IPath& rhs) +{ + return (lhs != rhs.getFullPath()); +} +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_IPATH_H_ diff --git a/src_mobile/modules/API/Filesystem/IStream.cpp b/src_mobile/modules/API/Filesystem/IStream.cpp new file mode 100644 index 0000000..b18f188 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/IStream.cpp @@ -0,0 +1,25 @@ +/* + * 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 "IStream.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +IStream::~IStream() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/IStream.h b/src_mobile/modules/API/Filesystem/IStream.h new file mode 100644 index 0000000..d39ddb0 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/IStream.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_ISTREAM_H_ +#define WRTDEVICEAPIS_FILESYSTEM_ISTREAM_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class IStream; +typedef DPL::SharedPtr 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 long getSize() const = 0; +}; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_ISTREAM_H_ */ diff --git a/src_mobile/modules/API/Filesystem/NodeFilter.cpp b/src_mobile/modules/API/Filesystem/NodeFilter.cpp new file mode 100644 index 0000000..b26e275 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/NodeFilter.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "NodeFilter.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +OptionalString NodeFilter::getName() const +{ + return m_name; +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/NodeFilter.h b/src_mobile/modules/API/Filesystem/NodeFilter.h new file mode 100644 index 0000000..3c47549 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/NodeFilter.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_NODEFILTER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_NODEFILTER_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +typedef DPL::Optional OptionalString; +typedef DPL::Optional OptionalDate; +typedef DPL::Optional OptionalSize; + +class NodeFilter +{ + public: + 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); + + private: + OptionalString m_name; + Commons::Range m_created; + Commons::Range m_modified; + Commons::Range m_size; +}; + +typedef DPL::SharedPtr NodeFilterPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_NODEFILTER_H_ diff --git a/src_mobile/modules/API/Filesystem/PathUtils.cpp b/src_mobile/modules/API/Filesystem/PathUtils.cpp new file mode 100644 index 0000000..e2ac7de --- /dev/null +++ b/src_mobile/modules/API/Filesystem/PathUtils.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "PathUtils.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +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) { + result.push_back(IPath::create(fullPath.substr(0, pos))); + } + return result; +} +} // PathUtils +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Filesystem/PathUtils.h b/src_mobile/modules/API/Filesystem/PathUtils.h new file mode 100644 index 0000000..40642f3 --- /dev/null +++ b/src_mobile/modules/API/Filesystem/PathUtils.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_PATHUTILS_H_ +#define WRTDEVICEAPIS_FILESYSTEM_PATHUTILS_H_ + +#include +#include "IPath.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +namespace PathUtils { +typedef std::vector 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 +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_PATHUTILS_H_ diff --git a/src_mobile/modules/API/Filesystem/config.cmake b/src_mobile/modules/API/Filesystem/config.cmake new file mode 100644 index 0000000..a9a514b --- /dev/null +++ b/src_mobile/modules/API/Filesystem/config.cmake @@ -0,0 +1,25 @@ +get_current_path() + +set(API_FILESYSTEM_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_FILESYSTEM + ${CURRENT_PATH}/IManager.cpp + ${CURRENT_PATH}/IPath.cpp + ${CURRENT_PATH}/IStream.cpp + ${CURRENT_PATH}/EventResolve.cpp + ${CURRENT_PATH}/EventCopy.cpp + ${CURRENT_PATH}/EventMove.cpp + ${CURRENT_PATH}/EventRemove.cpp + ${CURRENT_PATH}/EventFind.cpp + ${CURRENT_PATH}/EventListNodes.cpp + ${CURRENT_PATH}/EventOpen.cpp + ${CURRENT_PATH}/EventReadText.cpp + ${CURRENT_PATH}/INode.cpp + ${CURRENT_PATH}/NodeFilter.cpp + ${CURRENT_PATH}/PathUtils.cpp + PARENT_SCOPE +) + diff --git a/src_mobile/modules/API/LocalStorage/ILocalStorage.h b/src_mobile/modules/API/LocalStorage/ILocalStorage.h new file mode 100644 index 0000000..6ee677e --- /dev/null +++ b/src_mobile/modules/API/LocalStorage/ILocalStorage.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Local storage interface file + */ + +#ifndef WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_INTERFACE_H_ +#define WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_INTERFACE_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +class ILocalStorage +{ + public: + + /** + * Save pair key/value in local storage + * @param key + * @param value + * @param readOnly - if true, the value will be read only + * otherwise the value will be modificable + */ + virtual void setItem(const std::string& key, + const std::string& value, + bool readOnly) = 0; + + /** + * Remove pair key/value from local storage + */ + virtual void removeItem(const std::string& key) = 0; + + /** + * Get value for key + * + */ + virtual DPL::Optional getValue( + const std::string& key) const = 0; + + /** + * Clears the local storage + * @param removeReadOnly - true -remove all elements + * false - ommit items which have read only flag + * set + */ + virtual void clear(bool removeReadOnly) = 0; + + /** + * Get number of elements in local storage + * @param removeReadOnly - true -remove all elements + * false - ommit items which have read only flag + * set + */ + virtual size_t getStorageSize() const = 0; + + /** + * Get key name for index + */ + virtual std::string getKeyByIndex(size_t index) const = 0; + + /** + * virtual destructor + */ + virtual ~ILocalStorage() + {} +}; + +typedef DPL::SharedPtr ILocalStoragePtr; +} // Api +} // LocalStorage +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_LOCALSTORAGE_LOACA_STORAGE_INTERFACE_H_ diff --git a/src_mobile/modules/API/LocalStorage/LocalStorageMgr.cpp b/src_mobile/modules/API/LocalStorage/LocalStorageMgr.cpp new file mode 100644 index 0000000..04e9cc8 --- /dev/null +++ b/src_mobile/modules/API/LocalStorage/LocalStorageMgr.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file LocalStorageMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ +#include "LocalStorageMgr.h" +#include + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +ILocalStoragePtr getLocalStorage(int widgetId) +{ + return ILocalStoragePtr(new WrtDeviceApis::WidgetInterfaceObject(widgetId)); +} +} // Api +} // LocalStorage +} // WrtDeviceApis diff --git a/src_mobile/modules/API/LocalStorage/LocalStorageMgr.h b/src_mobile/modules/API/LocalStorage/LocalStorageMgr.h new file mode 100644 index 0000000..c892376 --- /dev/null +++ b/src_mobile/modules/API/LocalStorage/LocalStorageMgr.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file LocalStorageMgr.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H +#define WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H + +#include + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +ILocalStoragePtr getLocalStorage(int widgetId); +} // Api +} // LocalStorage +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H + diff --git a/src_mobile/modules/API/LocalStorage/config.cmake b/src_mobile/modules/API/LocalStorage/config.cmake new file mode 100644 index 0000000..f421686 --- /dev/null +++ b/src_mobile/modules/API/LocalStorage/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_LOCALSTORAGE_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_LOCALSTORAGE + ${CURRENT_PATH}/LocalStorageMgr.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/Networking/EventConnected.cpp b/src_mobile/modules/API/Networking/EventConnected.cpp new file mode 100644 index 0000000..51a5799 --- /dev/null +++ b/src_mobile/modules/API/Networking/EventConnected.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventConnected.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api {} // Api +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Networking/EventConnected.h b/src_mobile/modules/API/Networking/EventConnected.h new file mode 100644 index 0000000..26f5618 --- /dev/null +++ b/src_mobile/modules/API/Networking/EventConnected.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_EVENTCONNECTED_H_ +#define WRTDEVICEAPIS_NETWORKING_EVENTCONNECTED_H_ + +#include +#include +#include +#include "IConnection.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +/* TODO */ +class EventConnected : public Commons::ListenerEvent +{ + private: + IConnectionPtr m_connection; +}; + +typedef DPL::SharedPtr EventConnectedPtr; +typedef Commons::ListenerEventEmitter EventConnectedEmitter; +typedef DPL::SharedPtr EventConnectedEmitterPtr; +} // Api +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_EVENTCONNECTED_H_ diff --git a/src_mobile/modules/API/Networking/EventDisconnected.cpp b/src_mobile/modules/API/Networking/EventDisconnected.cpp new file mode 100644 index 0000000..7be367a --- /dev/null +++ b/src_mobile/modules/API/Networking/EventDisconnected.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventDisconnected.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api {} // Api +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Networking/EventDisconnected.h b/src_mobile/modules/API/Networking/EventDisconnected.h new file mode 100644 index 0000000..e683e9f --- /dev/null +++ b/src_mobile/modules/API/Networking/EventDisconnected.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_EVENTDISCONNECTED_H_ +#define WRTDEVICEAPIS_NETWORKING_EVENTDISCONNECTED_H_ + +#include +#include +#include +#include "IConnection.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +/* TODO */ +class EventDisconnected : public Commons::ListenerEvent +{ + private: + IConnectionPtr m_connection; +}; + +typedef DPL::SharedPtr EventDisconnectedPtr; +typedef Commons::ListenerEventEmitter +EventDisconnectedEmitter; +typedef DPL::SharedPtr EventDisconnectedEmitterPtr; +} // Api +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_EVENTDISCONNECTED_H_ diff --git a/src_mobile/modules/API/Networking/IAdapter.cpp b/src_mobile/modules/API/Networking/IAdapter.cpp new file mode 100644 index 0000000..5b94609 --- /dev/null +++ b/src_mobile/modules/API/Networking/IAdapter.cpp @@ -0,0 +1,25 @@ +/* + * 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 "IAdapter.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +IAdapter::~IAdapter() +{} +} // Api +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Networking/IAdapter.h b/src_mobile/modules/API/Networking/IAdapter.h new file mode 100644 index 0000000..9159022 --- /dev/null +++ b/src_mobile/modules/API/Networking/IAdapter.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_IADAPTER_H_ +#define WRTDEVICEAPIS_NETWORKING_IADAPTER_H_ + +#include +#include +#include "IConnection.h" +#include "EventConnected.h" +#include "EventDisconnected.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +class IAdapter : public DPL::Noncopyable +{ + public: + /** + * Adapter type. + */ + enum Type + { + T_ETHERNET, //!< T_ETHERNET + T_WIFI //!< T_WIFI + }; + + public: + virtual ~IAdapter() = 0; + + /** + * Checks whether network adapter has active connection. + * @return True when connected, false otherwsie. + */ + virtual bool isConnected() const = 0; + + /** + * Gets active connection. + * @return Active connection or NULL if not connected. + */ + virtual IConnectionPtr getConnection() const = 0; + + /** + * Sets on connected event emitter. + * @param event Event emitter. + */ + virtual void addOnConnected(const EventConnectedEmitterPtr& emitter) = 0; + + /** + * Removes on connected event emitter. + * @param id Emitters id. + */ + virtual void removeOnConnected(EventConnectedEmitter::IdType id) = 0; + + /** + * Sets on disconnected event emitter. + * @param emitter Event emitter. + */ + virtual void addOnDisconnected(const EventDisconnectedEmitterPtr& emitter) + = 0; + + /** + * Removes on disconnected event emitter. + * @param id Emitters id. + */ + virtual void removeOnDisconnected(EventDisconnectedEmitter::IdType id) = 0; + + /** + * Gets type of an adapter + * @return type Type of an adapter + */ + virtual Type getAdapterType() const = 0; +}; + +typedef std::list AdaptersSet; +typedef std::list::iterator AdaptersSetIterator; +} // Api +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_IADAPTER_H_ diff --git a/src_mobile/modules/API/Networking/IConnection.cpp b/src_mobile/modules/API/Networking/IConnection.cpp new file mode 100644 index 0000000..d8bc537 --- /dev/null +++ b/src_mobile/modules/API/Networking/IConnection.cpp @@ -0,0 +1,25 @@ +/* + * 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 "IConnection.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +IConnection::~IConnection() +{} +} // Api +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Networking/IConnection.h b/src_mobile/modules/API/Networking/IConnection.h new file mode 100644 index 0000000..eb0202d --- /dev/null +++ b/src_mobile/modules/API/Networking/IConnection.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_ICONNECTION_H_ +#define WRTDEVICEAPIS_NETWORKING_ICONNECTION_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +class IConnection : public DPL::Noncopyable +{ + public: + virtual ~IConnection() = 0; + + /** + * Gets connection name. + * @return Connection's name. + */ + virtual std::string getName() const = 0; +}; + +typedef DPL::SharedPtr IConnectionPtr; +} // Api +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_ICONNECTION_H_ diff --git a/src_mobile/modules/API/Networking/IManager.cpp b/src_mobile/modules/API/Networking/IManager.cpp new file mode 100644 index 0000000..fd3f216 --- /dev/null +++ b/src_mobile/modules/API/Networking/IManager.cpp @@ -0,0 +1,31 @@ +/* + * 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 +#include "IManager.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +IManager& IManager::getInstance() +{ + return Manager::getInstance(); +} + +IManager::~IManager() +{} +} // Api +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/API/Networking/IManager.h b/src_mobile/modules/API/Networking/IManager.h new file mode 100644 index 0000000..841316a --- /dev/null +++ b/src_mobile/modules/API/Networking/IManager.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_IMANAGER_H_ +#define WRTDEVICEAPIS_NETWORKING_IMANAGER_H_ + +#include +#include "IAdapter.h" + +namespace WrtDeviceApis { +namespace Networking { +namespace Api { +class IManager : private DPL::Noncopyable +{ + public: + static IManager& getInstance(); + + public: + virtual ~IManager() = 0; + + /** + * Gets specfied adapter. + * @param type Adapter type @see IAdapter::Type. + * @return Interface to network adapter, NULL if current platform does not + * support such network adapter. + * @throw PlatformException If platform error occured. + */ + virtual IAdapter* getAdapter(IAdapter::Type type) const = 0; + + /** + * Adds to given set all available on platform adapters + * @param [out] list of interfaces to network adapters + */ + virtual void getAvailableAdapters(AdaptersSet *retSet) const = 0; +}; +} // Api +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_IMANAGER_H_ diff --git a/src_mobile/modules/API/Networking/config.cmake b/src_mobile/modules/API/Networking/config.cmake new file mode 100644 index 0000000..66ab813 --- /dev/null +++ b/src_mobile/modules/API/Networking/config.cmake @@ -0,0 +1,15 @@ +get_current_path() + +set(API_NETWORKING_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_NETWORKING + ${CURRENT_PATH}/IManager.cpp + ${CURRENT_PATH}/IAdapter.cpp + ${CURRENT_PATH}/IConnection.cpp + ${CURRENT_PATH}/EventConnected.cpp + ${CURRENT_PATH}/EventDisconnected.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/PluginManager/IPluginManager.h b/src_mobile/modules/API/PluginManager/IPluginManager.h new file mode 100644 index 0000000..d96652c --- /dev/null +++ b/src_mobile/modules/API/PluginManager/IPluginManager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IPluginManager.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ +#define WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +class IPluginManager +{ + public: + typedef std::vector PropertyList; + + virtual ~IPluginManager() {} + virtual bool hasChild(const std::string &name) const = 0; + virtual bool loadChild(const std::string &name) const = 0; + + virtual JSValueRef getProperty(const std::string &name) const = 0; + virtual bool setProperty(const std::string &name, + JSValueRef value) = 0; + virtual bool deleteProperty(const std::string &name) = 0; + + virtual PropertyList getProperties() const = 0; + virtual void addPropertiesToList( + JSPropertyNameAccumulatorRef propertyNames) const = 0; +}; + +typedef DPL::SharedPtr IPluginManagerPtr; +} +} +} + +#endif // WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ diff --git a/src_mobile/modules/API/PluginManager/PluginManagerFactory.cpp b/src_mobile/modules/API/PluginManager/PluginManagerFactory.cpp new file mode 100644 index 0000000..3866028 --- /dev/null +++ b/src_mobile/modules/API/PluginManager/PluginManagerFactory.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file PluginManagerFactory.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#include "PluginManagerFactory.h" +#include + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +PluginManagerFactory::PluginManagerFactory() +{} + +PluginManagerFactory& PluginManagerFactory::getInstance() +{ + static PluginManagerFactory instance; + return instance; +} + +IPluginManagerPtr PluginManagerFactory::getPluginManager( + int widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context) const +{ + return IPluginManagerPtr( + new PluginManager(widgetHandle, objectUri, object, context)); +} +} +} +} diff --git a/src_mobile/modules/API/PluginManager/PluginManagerFactory.h b/src_mobile/modules/API/PluginManager/PluginManagerFactory.h new file mode 100644 index 0000000..b13a36a --- /dev/null +++ b/src_mobile/modules/API/PluginManager/PluginManagerFactory.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file PluginManagerFactory.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ +#define WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +class PluginManagerFactory : private DPL::Noncopyable +{ + public: + static PluginManagerFactory& getInstance(); + IPluginManagerPtr getPluginManager( + int widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context) const; + + private: + PluginManagerFactory(); +}; +} +} +} + +#endif // WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ diff --git a/src_mobile/modules/API/PluginManager/config.cmake b/src_mobile/modules/API/PluginManager/config.cmake new file mode 100644 index 0000000..f513d08 --- /dev/null +++ b/src_mobile/modules/API/PluginManager/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_PLUGIN_MANAGER_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_PLUGIN_MANAGER + ${CURRENT_PATH}/PluginManagerFactory.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h b/src_mobile/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h new file mode 100644 index 0000000..a001b71 --- /dev/null +++ b/src_mobile/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file ISoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event interfece + */ + +#ifndef WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H +#define WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H + +#include + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +class ISoftKeyboardChangeEvent +{ + public: + virtual std::string getState() const = 0; + virtual int getWidth() const = 0; + virtual int getHeight() const = 0; + + virtual ~ISoftKeyboardChangeEvent() {} +}; + +typedef std::shared_ptr ISoftKeyboardChangeEventPtr; +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis + +#endif // WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H diff --git a/src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp b/src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp new file mode 100644 index 0000000..7cd04ba --- /dev/null +++ b/src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file SoftKeyboardChangeEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event class implementation + */ + +#include "SoftKeyboardChangeEvent.h" + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +SoftKeyboardChangeEvent::SoftKeyboardChangeEvent( + std::string state, int width, int height) : + m_state(state), m_width(width), m_height(height) +{} + +SoftKeyboardChangeEvent::~SoftKeyboardChangeEvent() +{} + +std::string SoftKeyboardChangeEvent::getState() const +{ + return m_state; +} + +int SoftKeyboardChangeEvent::getWidth() const +{ + return m_width; +} + +int SoftKeyboardChangeEvent::getHeight() const +{ + return m_height; +} +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis diff --git a/src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h b/src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h new file mode 100644 index 0000000..df8f721 --- /dev/null +++ b/src_mobile/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file SoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event class + */ + +#ifndef WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H +#define WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H + +#include +#include "ISoftKeyboardChangeEvent.h" + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +class SoftKeyboardChangeEvent : public ISoftKeyboardChangeEvent +{ + public: + explicit SoftKeyboardChangeEvent( + std::string state, + int width, + int height); + ~SoftKeyboardChangeEvent(); + + std::string getState() const; + int getWidth() const; + int getHeight() const; + + private: + std::string m_state; + int m_width; + int m_height; +}; +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis + +#endif // WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H diff --git a/src_mobile/modules/API/SoftKeyboardChangeEvent/config.cmake b/src_mobile/modules/API/SoftKeyboardChangeEvent/config.cmake new file mode 100644 index 0000000..398a39b --- /dev/null +++ b/src_mobile/modules/API/SoftKeyboardChangeEvent/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_SOFTKEYBOARD_CHANGE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_SOFTKEYBOARD_CHANGE_EVENT + ${CURRENT_PATH}/SoftKeyboardChangeEvent.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/StorageEvent/IStorageEvent.h b/src_mobile/modules/API/StorageEvent/IStorageEvent.h new file mode 100644 index 0000000..5c34514 --- /dev/null +++ b/src_mobile/modules/API/StorageEvent/IStorageEvent.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file IStorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event interfece + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H +#define WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H + +#include +#include +#include + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +class IStorageEvent +{ + public: + + virtual std::string getKey() const = 0; + virtual DPL::OptionalString getOldValue() const = 0; + virtual DPL::OptionalString getNewValue() const = 0; + virtual std::string getUrl() const = 0; + virtual LocalStorage::Api::ILocalStoragePtr getStorageArea() const = 0; + + virtual void setKey(const std::string &inKey) = 0; + virtual void setOldValue(const std::string &inValue) = 0; + virtual void setNewValue(const std::string &inValue) = 0; + virtual void setUrl(const std::string &inUrl) = 0; + virtual void setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea) = 0; +}; + +typedef DPL::SharedPtr IStorageEventPtr; +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H diff --git a/src_mobile/modules/API/StorageEvent/StorageEvent.cpp b/src_mobile/modules/API/StorageEvent/StorageEvent.cpp new file mode 100644 index 0000000..11068b7 --- /dev/null +++ b/src_mobile/modules/API/StorageEvent/StorageEvent.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEvent.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event class implementation + */ + +#include "StorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +StorageEvent::StorageEvent() : + m_storageArea(NULL) {} + +StorageEvent::StorageEvent( + const LocalStorage::Api::ILocalStoragePtr &storageArea) : + m_storageArea(storageArea) {} + +std::string StorageEvent::getKey() const +{ + return m_key; +} + +DPL::OptionalString StorageEvent::getOldValue() const +{ + return m_oldValue; +} + +DPL::OptionalString StorageEvent::getNewValue() const +{ + return m_newValue; +} +std::string StorageEvent::getUrl() const +{ + return m_url; +} + +LocalStorage::Api::ILocalStoragePtr StorageEvent::getStorageArea() const +{ + return m_storageArea; +} + +void StorageEvent::setKey(const std::string &inKey) +{ + m_key = inKey; +} + +void StorageEvent::setOldValue(const std::string &inValue) +{ + m_oldValue = DPL::FromUTF8String(inValue); +} + +void StorageEvent::setNewValue(const std::string &inValue) +{ + m_newValue = DPL::FromUTF8String(inValue); +} + +void StorageEvent::setUrl(const std::string &inUrl) +{ + m_url = inUrl; +} + +void StorageEvent::setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea) +{ + m_storageArea = inStorageArea; +} +} // Api +} // StorageEvent +} // WrtDeviceApis diff --git a/src_mobile/modules/API/StorageEvent/StorageEvent.h b/src_mobile/modules/API/StorageEvent/StorageEvent.h new file mode 100644 index 0000000..37df421 --- /dev/null +++ b/src_mobile/modules/API/StorageEvent/StorageEvent.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event class + */ + +#ifndef WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H +#define WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H + +#include +#include "IStorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +class StorageEvent : public IStorageEvent +{ + public: + + StorageEvent(); + explicit StorageEvent( + const LocalStorage::Api::ILocalStoragePtr &storageArea); + + std::string getKey() const; + DPL::OptionalString getOldValue() const; + DPL::OptionalString getNewValue() const; + std::string getUrl() const; + LocalStorage::Api::ILocalStoragePtr getStorageArea() const; + + void setKey(const std::string &inKey); + void setOldValue(const std::string &inValue); + void setNewValue(const std::string &inValue); + void setUrl(const std::string &inUrl); + void setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea); + + private: + std::string m_key; + DPL::OptionalString m_oldValue; + DPL::OptionalString m_newValue; + std::string m_url; + LocalStorage::Api::ILocalStoragePtr m_storageArea; +}; +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H diff --git a/src_mobile/modules/API/StorageEvent/StorageEventMgr.cpp b/src_mobile/modules/API/StorageEvent/StorageEventMgr.cpp new file mode 100644 index 0000000..92b8772 --- /dev/null +++ b/src_mobile/modules/API/StorageEvent/StorageEventMgr.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEventMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event getter + */ + +#include "StorageEventMgr.h" +#include "StorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +IStorageEventPtr getStorageEvent() +{ + return IStorageEventPtr(new StorageEvent()); +} +} // Api +} // StorageEvent +} // WrtDeviceApis diff --git a/src_mobile/modules/API/StorageEvent/StorageEventMgr.h b/src_mobile/modules/API/StorageEvent/StorageEventMgr.h new file mode 100644 index 0000000..b519abd --- /dev/null +++ b/src_mobile/modules/API/StorageEvent/StorageEventMgr.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEventMgr.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event interfece + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H +#define WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H + +#include "IStorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +IStorageEventPtr getStorageEvent(); +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H + diff --git a/src_mobile/modules/API/StorageEvent/config.cmake b/src_mobile/modules/API/StorageEvent/config.cmake new file mode 100644 index 0000000..a0029fc --- /dev/null +++ b/src_mobile/modules/API/StorageEvent/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(API_STORAGE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_STORAGE_EVENT + ${CURRENT_PATH}/StorageEventMgr.cpp + ${CURRENT_PATH}/StorageEvent.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/TizenServiceEvent/ITizenServiceEvent.h b/src_mobile/modules/API/TizenServiceEvent/ITizenServiceEvent.h new file mode 100644 index 0000000..8882b69 --- /dev/null +++ b/src_mobile/modules/API/TizenServiceEvent/ITizenServiceEvent.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file ITizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen Service event interfece + */ + +#ifndef _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ +#define _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +class ITizenServiceEvent +{ + public: + virtual float getScale() const = 0; + virtual std::string getBundle() const = 0; + + virtual void setScale(const float scale) = 0; + virtual void setBundle(const std::string &bundle) = 0; + virtual ~ITizenServiceEvent() {} +}; + +typedef DPL::SharedPtr ITizenServiceEventPtr; +} // Api +} // TizenServiceEvent +} // WrtDeviceApis + +#endif // _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ diff --git a/src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.cpp b/src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.cpp new file mode 100644 index 0000000..b6233c6 --- /dev/null +++ b/src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file TizenServiceEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen appservice event class implementation + */ + +#include "TizenServiceEvent.h" + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +TizenServiceEvent::TizenServiceEvent() : + m_scale(0) +{} + +TizenServiceEvent::~TizenServiceEvent() +{} + +float TizenServiceEvent::getScale() const +{ + return m_scale; +} + +std::string TizenServiceEvent::getBundle() const +{ + return m_bundle; +} + +void TizenServiceEvent::setScale(const float scale) +{ + m_scale = scale; +} + +void TizenServiceEvent::setBundle(const std::string& bundle) +{ + m_bundle = bundle; +} +} // Api +} // TizenServiceEvent +} // WrtDeviceApis diff --git a/src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.h b/src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.h new file mode 100644 index 0000000..3b577f0 --- /dev/null +++ b/src_mobile/modules/API/TizenServiceEvent/TizenServiceEvent.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file TizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen Service event class + */ + +#ifndef _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ +#define _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ + +#include +#include "ITizenServiceEvent.h" + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +class TizenServiceEvent : public ITizenServiceEvent +{ + public: + + TizenServiceEvent(); + ~TizenServiceEvent(); + + float getScale() const; + std::string getBundle() const; + + void setScale(const float scale); + void setBundle(const std::string &bundle); + + private: + float m_scale; + std::string m_bundle; +}; +} // Api +} // TizenServiceEvent +} // WrtDeviceApis + +#endif // _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ diff --git a/src_mobile/modules/API/TizenServiceEvent/config.cmake b/src_mobile/modules/API/TizenServiceEvent/config.cmake new file mode 100644 index 0000000..5a64dcd --- /dev/null +++ b/src_mobile/modules/API/TizenServiceEvent/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_TIZEN_SERVICE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_TIZEN_SERVICE_EVENT + ${CURRENT_PATH}/TizenServiceEvent.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/Widget/IWidget.h b/src_mobile/modules/API/Widget/IWidget.h new file mode 100644 index 0000000..1936ee9 --- /dev/null +++ b/src_mobile/modules/API/Widget/IWidget.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file IWidget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef INTERFACE_WIDGET_CONFIG_INFO_H +#define INTERFACE_WIDGET_CONFIG_INFO_H + +#include + +#include + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +class IWidget; +typedef DPL::SharedPtr IWidgetPtr; + +class IWidget +{ + public: // methods + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthor() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthorEmail() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthorHref() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getDescription() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getId() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getName() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getShortName() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getVersion() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual unsigned int getHeight() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual unsigned int getWidth() const = 0; + + virtual ~IWidget() + {} +}; +} +} +} + +#endif diff --git a/src_mobile/modules/API/Widget/WidgetFactory.cpp b/src_mobile/modules/API/Widget/WidgetFactory.cpp new file mode 100644 index 0000000..2197a75 --- /dev/null +++ b/src_mobile/modules/API/Widget/WidgetFactory.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file WidgetFactory.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#include "WidgetFactory.h" + +#include + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +IWidgetPtr WidgetFactory::createWidget() +{ + return IWidgetPtr(new WrtDeviceApis::Widget::Widget()); +} +} +} +} diff --git a/src_mobile/modules/API/Widget/WidgetFactory.h b/src_mobile/modules/API/Widget/WidgetFactory.h new file mode 100644 index 0000000..b068dc2 --- /dev/null +++ b/src_mobile/modules/API/Widget/WidgetFactory.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file WidgetFactory.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef _WIDGET_FACTORY_H +#define _WIDGET_FACTORY_H + +#include +#include +#include + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +class WidgetFactory : private DPL::Noncopyable +{ + public: + + /** + * Create widget + * @param[in] id of the widget + */ + static IWidgetPtr createWidget(); + + private: + WidgetFactory() + {} +}; +} +} +} + +#endif diff --git a/src_mobile/modules/API/Widget/config.cmake b/src_mobile/modules/API/Widget/config.cmake new file mode 100644 index 0000000..11ffcc8 --- /dev/null +++ b/src_mobile/modules/API/Widget/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_WIDGET_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_WIDGET + ${CURRENT_PATH}/WidgetFactory.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/API/WidgetDB/IWidgetDB.h b/src_mobile/modules/API/WidgetDB/IWidgetDB.h new file mode 100644 index 0000000..e0c3f9b --- /dev/null +++ b/src_mobile/modules/API/WidgetDB/IWidgetDB.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IWidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Widget interface to access WRT DB + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_IWIDGETDB_H_ +#define WRTDEVICEAPIS_WIDGETDB_IWIDGETDB_H_ + +#include "IWidgetFeature.h" +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +class IWidgetDB; +typedef DPL::SharedPtr IWidgetDBPtr; + +typedef std::vector Features; + +enum class ConfigAttribute +{ + ID, + VERSION, + DESCRIPTION, + LICENSE, + LICENSE_HREF, + AUTHOR_NAME, + AUTHOR_HREF, + AUTHOR_EMAIL, + NAME, + SHORT_NAME, + ICON, + ACCESS_NETWORK, + WIDTH, + HEIGHT, + INSTALL_PATH, + PUBLIC_STORAGE_PATH +}; + +enum class InstallationStatus +{ + STATUS_INSTALLED, + STATUS_LATEST, + STATUS_UNINSTALLED +}; + +class IWidgetDB +{ + public: + + virtual int getWidgetId() const = 0; + + virtual std::string getLanguage() const = 0; + + virtual std::string getConfigValue(ConfigAttribute attribute) const = 0; + + virtual std::string getUserAgent() const = 0; + + virtual InstallationStatus checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const = 0; + + virtual Features getWidgetFeatures() const = 0; + + virtual Features getRegisteredFeatures() const = 0; + + virtual std::string getWidgetInstallationPath() const = 0; + + virtual std::string getWidgetPersistentStoragePath() const = 0; + + virtual std::string getWidgetTemporaryStoragePath() const = 0; + + virtual ~IWidgetDB() + {} +}; +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif + diff --git a/src_mobile/modules/API/WidgetDB/IWidgetFeature.h b/src_mobile/modules/API/WidgetDB/IWidgetFeature.h new file mode 100644 index 0000000..2371c1e --- /dev/null +++ b/src_mobile/modules/API/WidgetDB/IWidgetFeature.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_INTERFACE_H_ +#define WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_INTERFACE_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +class IWidgetFeature +{ + public: + + virtual ~IWidgetFeature() + {} + + virtual std::string getName() const = 0; + + virtual bool isRequestedByWidget() const = 0; +}; + +typedef DPL::SharedPtr IWidgetFeaturePtr; +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif diff --git a/src_mobile/modules/API/WidgetDB/WidgetDBMgr.cpp b/src_mobile/modules/API/WidgetDB/WidgetDBMgr.cpp new file mode 100644 index 0000000..b275f33 --- /dev/null +++ b/src_mobile/modules/API/WidgetDB/WidgetDBMgr.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IWidgetDBMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "IWidgetDB.h" +#include "WidgetDBMgr.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +IWidgetDBPtr getWidgetDB(int widgetId) +{ + return IWidgetDBPtr(new WrtDeviceApis::WidgetDB::WidgetDB(widgetId)); +} +} // Api +} // WidgetDB +} // WrtDeviceApis diff --git a/src_mobile/modules/API/WidgetDB/WidgetDBMgr.h b/src_mobile/modules/API/WidgetDB/WidgetDBMgr.h new file mode 100644 index 0000000..6de3f99 --- /dev/null +++ b/src_mobile/modules/API/WidgetDB/WidgetDBMgr.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IWidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Widget interface to access WRT DB + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H +#define WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H + +#include "IWidgetDB.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +IWidgetDBPtr getWidgetDB(int widgetId); +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H + diff --git a/src_mobile/modules/API/WidgetDB/config.cmake b/src_mobile/modules/API/WidgetDB/config.cmake new file mode 100644 index 0000000..14a6acc --- /dev/null +++ b/src_mobile/modules/API/WidgetDB/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(API_WIDGETDB_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_WIDGETDB + ${CURRENT_PATH}/WidgetDBMgr.cpp + PARENT_SCOPE +) + diff --git a/src_mobile/modules/API/config.cmake b/src_mobile/modules/API/config.cmake new file mode 100644 index 0000000..82b25da --- /dev/null +++ b/src_mobile/modules/API/config.cmake @@ -0,0 +1,3 @@ +include_config_file(Widget) +include_config_file(StorageEvent) +include_config_file(LocalStorage) \ No newline at end of file diff --git a/src_mobile/modules/CMakeLists.txt b/src_mobile/modules/CMakeLists.txt new file mode 100644 index 0000000..85db759 --- /dev/null +++ b/src_mobile/modules/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/${PLATFORM} +) + +add_subdirectory(API) +add_subdirectory(${PLATFORM}) +add_subdirectory(packages) diff --git a/src_mobile/modules/DESCRIPTION b/src_mobile/modules/DESCRIPTION new file mode 100644 index 0000000..a5d1510 --- /dev/null +++ b/src_mobile/modules/DESCRIPTION @@ -0,0 +1 @@ +Platform abstraction diff --git a/src_mobile/modules/packages/CMakeLists.txt b/src_mobile/modules/packages/CMakeLists.txt new file mode 100644 index 0000000..ed3e799 --- /dev/null +++ b/src_mobile/modules/packages/CMakeLists.txt @@ -0,0 +1,34 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set(TARGET_MODULE_FILESYSTEM "wrt-plugins-filesystem") +set(TARGET_MODULE_WIDGET "wrt-plugins-widget") +set(TARGET_MODULE_LOCALSTORAGE "wrt-plugins-localstorage") +set(TARGET_MODULE_WIDGET_INTERFACE "wrt-plugins-widget-interface") +set(TARGET_MODULE_STORAGEEVENT "wrt-plugins-storageevent") +set(TARGET_MODULE_TIZEN_SERVICE_EVENT "wrt-plugins-tizen-service-event") +set(TARGET_MODULE_SOFTKEYBOARD_CHANGE_EVENT "wrt-plugins-softkeyboardchange-event") +set(TARGET_MODULE_WIDGETDB "wrt-plugins-widgetdb") +set(TARGET_MODULE_PLUGIN_MANAGER "wrt-plugins-plugin-manager") + +add_subdirectory(Filesystem) +add_subdirectory(Widget) +add_subdirectory(LocalStorage) +add_subdirectory(WidgetInterface) +add_subdirectory(WidgetDB) +add_subdirectory(PluginManager) +add_subdirectory(StorageEvent) +add_subdirectory(TizenServiceEvent) +add_subdirectory(SoftKeyboardChangeEvent) diff --git a/src_mobile/modules/packages/Filesystem/CMakeLists.txt b/src_mobile/modules/packages/Filesystem/CMakeLists.txt new file mode 100644 index 0000000..e5079dc --- /dev/null +++ b/src_mobile/modules/packages/Filesystem/CMakeLists.txt @@ -0,0 +1,54 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_FILESYSTEM_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/Filesystem) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_FILESYSTEM}) + +set(SRCS + ${SRCS_API_FILESYSTEM} + ${SRCS_PLATFORM_IMPLEMENTATION_FILESYSTEM} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(IManager.h) +install_header_file(INode.h) +install_header_file(INodeTypes.h) +install_header_file(IPath.h) +install_header_file(IStream.h) +install_header_file(EventResolve.h) +install_header_file(EventCopy.h) +install_header_file(EventMove.h) +install_header_file(EventRemove.h) +install_header_file(EventFind.h) +install_header_file(EventListNodes.h) +install_header_file(EventOpen.h) +install_header_file(EventReadText.h) +install_header_file(Enums.h) +install_header_file(NodeFilter.h) diff --git a/src_mobile/modules/packages/LocalStorage/CMakeLists.txt b/src_mobile/modules/packages/LocalStorage/CMakeLists.txt new file mode 100644 index 0000000..90d648a --- /dev/null +++ b/src_mobile/modules/packages/LocalStorage/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +set(TARGET_NAME ${TARGET_MODULE_LOCALSTORAGE}) + +set(SRCS + ${SRCS_API_LOCALSTORAGE} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${TARGET_MODULE_WIDGET_INTERFACE} +) + diff --git a/src_mobile/modules/packages/Networking/CMakeLists.txt b/src_mobile/modules/packages/Networking/CMakeLists.txt new file mode 100644 index 0000000..9de7e04 --- /dev/null +++ b/src_mobile/modules/packages/Networking/CMakeLists.txt @@ -0,0 +1,50 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_NETWORKING_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/Networking) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_NETWORKING}) + +include_directories( + ${INCLUDES_PLATFORM_IMPLEMENTATION_NETWORKING} +) + +set(SRCS + ${SRCS_API_NETWORKING} + ${SRCS_IMPLEMENTATION_NETWORKING} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${LIBS_PLATFORM_IMPLEMENTATION_NETWORKING} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(EventConnected.h) +install_header_file(EventDisconnected.h) +install_header_file(IAdapter.h) +install_header_file(IConnection.h) +install_header_file(IManager.h) diff --git a/src_mobile/modules/packages/PluginManager/CMakeLists.txt b/src_mobile/modules/packages/PluginManager/CMakeLists.txt new file mode 100644 index 0000000..a66bbfd --- /dev/null +++ b/src_mobile/modules/packages/PluginManager/CMakeLists.txt @@ -0,0 +1,58 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# + +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_PLUGIN_MANAGER_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/PluginManager) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_PLUGIN_MANAGER}) + +pkg_search_module(webkit2 REQUIRED ewebkit2) + +include_directories( + ${INCLUDES_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} + ${webkit2_INCLUDE_DIRS}} +) + +set(SRCS + ${SRCS_API_PLUGIN_MANAGER} + ${SRCS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_PLUGIN_LOADING_LIB} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} + ${LIBS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} +) + +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(PluginManagerFactory.h) +install_header_file(IPluginManager.h) diff --git a/src_mobile/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt b/src_mobile/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt new file mode 100644 index 0000000..84b9944 --- /dev/null +++ b/src_mobile/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 0.1 + +set(TARGET_NAME ${TARGET_MODULE_SOFTKEYBOARD_CHANGE_EVENT}) + +set(SRCS + ${SRCS_API_SOFTKEYBOARD_CHANGE_EVENT} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) diff --git a/src_mobile/modules/packages/StorageEvent/CMakeLists.txt b/src_mobile/modules/packages/StorageEvent/CMakeLists.txt new file mode 100644 index 0000000..dc9ff0d --- /dev/null +++ b/src_mobile/modules/packages/StorageEvent/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +set(TARGET_NAME ${TARGET_MODULE_STORAGEEVENT}) + +set(SRCS + ${SRCS_API_STORAGE_EVENT} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${TARGET_MODULE_LOCALSTORAGE} +) + diff --git a/src_mobile/modules/packages/TizenServiceEvent/CMakeLists.txt b/src_mobile/modules/packages/TizenServiceEvent/CMakeLists.txt new file mode 100644 index 0000000..e8efc16 --- /dev/null +++ b/src_mobile/modules/packages/TizenServiceEvent/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 0.1 + +set(TARGET_NAME ${TARGET_MODULE_TIZEN_SERVICE_EVENT}) + +set(SRCS + ${SRCS_API_TIZEN_SERVICE_EVENT} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) diff --git a/src_mobile/modules/packages/Widget/CMakeLists.txt b/src_mobile/modules/packages/Widget/CMakeLists.txt new file mode 100644 index 0000000..74bf1a6 --- /dev/null +++ b/src_mobile/modules/packages/Widget/CMakeLists.txt @@ -0,0 +1,30 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set(TARGET_NAME ${TARGET_MODULE_WIDGET}) + +set(SRCS + ${SRCS_API_WIDGET} + ${SRCS_IMPLEMENTATION_WIDGET} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${TARGET_MODULE_WIDGETDB} +) + diff --git a/src_mobile/modules/packages/WidgetDB/CMakeLists.txt b/src_mobile/modules/packages/WidgetDB/CMakeLists.txt new file mode 100644 index 0000000..ec91fdb --- /dev/null +++ b/src_mobile/modules/packages/WidgetDB/CMakeLists.txt @@ -0,0 +1,50 @@ +# +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_WIDGETDB_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/WidgetDB) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_WIDGETDB}) + +include_directories( + ${INCLUDES_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +set(SRCS + ${SRCS_API_WIDGETDB} + ${SRCS_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${LIBS_PLATFORM_IMPLEMENTATION_WIDGETDB} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(IWidgetDB.h) +install_header_file(IWidgetFeature.h) +install_header_file(WidgetDBMgr.h) + diff --git a/src_mobile/modules/packages/WidgetInterface/CMakeLists.txt b/src_mobile/modules/packages/WidgetInterface/CMakeLists.txt new file mode 100644 index 0000000..0ebb5e2 --- /dev/null +++ b/src_mobile/modules/packages/WidgetInterface/CMakeLists.txt @@ -0,0 +1,50 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_WIDGET_INTERFACE_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/WidgetInterface) +endmacro() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(wrt-commons-widget-interface-dao REQUIRED wrt-commons-widget-interface-dao) + +include_directories( + ${WIDGET_INTERFACE_INCLUDE_DIRS} + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${wrt-commons-widget-interface-dao_INCLUDE_DIRS}) + +set(TARGET_NAME ${TARGET_MODULE_WIDGET_INTERFACE}) + +set(SRCS + ${SRCS_WIDGET_INTERFACE} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${dpl-wrt-dao-ro_LIBRARIES} + ${wrt-commons-widget-interface-dao_LIBRARIES} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(WidgetInterface.h) diff --git a/src_mobile/modules/tizen/CMakeLists.txt b/src_mobile/modules/tizen/CMakeLists.txt new file mode 100644 index 0000000..3cfc293 --- /dev/null +++ b/src_mobile/modules/tizen/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +############################################################################### +# In this section please add modules that shouldn't be visible directly +# beyond wac/ subdirectory, i.e. platform wrappers specific for wac - +# - used only as helpers in AL for wac platform implementation. VConf +# is a good example, its used i.e. in Power/Battery. Unfortunately order in +# in which this modules and AL modules are included is significant, i.e. VConf +# needs to be included before Power as there are some CMake variables set that +# are used in Power config.cmake file. +################################################################################ + +include_config_file(Filesystem) +include_config_file(Widget) +include_config_file(LocalStorage) +include_config_file(WidgetInterface) +add_subdirectory(WidgetInterface) +include_config_file(WidgetDB) +include_config_file(PluginManager) diff --git a/src_mobile/modules/tizen/DESCRIPTION b/src_mobile/modules/tizen/DESCRIPTION new file mode 100644 index 0000000..45900ba --- /dev/null +++ b/src_mobile/modules/tizen/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +API implementation for tizen platform diff --git a/src_mobile/modules/tizen/Filesystem/Manager.cpp b/src_mobile/modules/tizen/Filesystem/Manager.cpp new file mode 100644 index 0000000..5ecfe2f --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Manager.cpp @@ -0,0 +1,623 @@ +/* + * 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 "Manager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Node.h" +#include "Utils.h" + +namespace { +const char* PATH_ROOT = "/opt/media"; +const char* PATH_DOWNLOADS = "/opt/media/Downloads"; +const char* PATH_DOCUMENTS = "/opt/media/Documents"; +const char* PATH_SOUNDS = "/opt/media/Music"; +const char* PATH_IMAGES = "/opt/media/Images"; +const char* PATH_VIDEOS = "/opt/media/Videos"; +const char* PATH_SDCARD = "/opt/storage/sdcard"; +} + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +Manager::Locations Manager::m_locations; +const std::size_t Manager::m_maxPathLength = 256; +NodeList Manager::m_openedNodes; + +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."); +} + +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 +{ + Assert(path); + NodeListIterator it = m_openedNodes.begin(); + for (; it != m_openedNodes.end(); ++it) { + Assert(*it); + if (*path == *(*it)->getPath()) { + return true; + } + } + return false; +} + +Manager::Manager() +{ + static bool initialized = init(); + (void) initialized; +} + +Manager::~Manager() +{} + +IPathPtr Manager::getBasePath() const +{ + Locations::const_iterator it = m_locations.find(LT_ROOT); + 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(type); + 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; + Locations::const_iterator it = m_locations.begin(); + for (; it != m_locations.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +void Manager::getNode(const EventResolvePtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +std::size_t Manager::getMaxPathLength() const +{ + return m_maxPathLength; +} + +void Manager::copy(const EventCopyPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::move(const EventMovePtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::remove(const EventRemovePtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::find(const EventFindPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::find(const IPathPtr& path, + const FiltersMap& filters, + NodeList& result, + const EventFindPtr& event) +{ + Try { + Assert(path && "path is NULL"); + FTS *fts; + FTSENT *ftsent; + std::string pth = path->getFullPath(); + char * const paths[] = { const_cast(pth.c_str()), NULL }; + + if ((fts = + fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) + { + //ERROR + int error = errno; + LogError(__PRETTY_FUNCTION__ << ": fts_open on " + << pth + << " failed with error: " + << strerror(error)); + return; + } + + while ((ftsent = fts_read(fts)) != NULL) { + if (event && event->checkCancelled()) { + break; + } + switch (ftsent->fts_info) { + case FTS_DP: + //directory in postorder - do nothing + break; + case FTS_D: + case FTS_DC: + case FTS_F: + case FTS_SL: + case FTS_SLNONE: + case FTS_DEFAULT: + //regular files, symbolic links, directories in preorder + //and other file entries that can be processed further + if (matchFilters(ftsent->fts_name, *ftsent->fts_statp, + filters)) + { + IPathPtr childPath = IPath::create(ftsent->fts_path); + result.push_back(Node::resolve(childPath)); + } + break; + case FTS_NS: + case FTS_NSOK: + case FTS_DOT: + case FTS_DNR: + case FTS_ERR: + default: + LogWarning(__PRETTY_FUNCTION__ + << ": traversal failed with error: " + << strerror(ftsent->fts_errno)); + ThrowMsg(Commons::PlatformException, + "Error reading directory"); + } + } + + if (fts_close(fts) == -1) { + int error = errno; + LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: " + << strerror(error)); + ThrowMsg(Commons::PlatformException, + "Could not close platform node."); + } + } + Catch(Commons::Exception) {} +} + +void Manager::copyElement( + const std::string &src, const std::string &dest, bool recursive) const +{ + LogDebug("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_mkdir(dest.c_str())) { + LogDebug("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(data)).c_str(), + (dest + '/' + static_cast(data)).c_str()); + } + Catch(Commons::PlatformException) + { + //remove rest of the list + EINA_LIST_FREE(list, data) + { + free(data); + } + 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); +} + +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(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 { + event->setResult(Node::resolve(event->getPath())); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + event->setCancelAllowed(true); +} + +void Manager::checkPaths( + Api::IPathPtr &src, + Api::IPathPtr &dest) +{ + Assert(dest); + Assert(src); + if (!dest->isAbsolute()) { + dest = src->getPath() + *dest; + } + + if (src == dest) { + ThrowMsg(Commons::PlatformException, + "Destination is same as source: " << src->getFullPath()); + } + + INodePtr parent; + Try { + parent = Node::resolve(IPath::create(dest->getPath())); + } + Catch(Commons::PlatformException) { + 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."); + } + + if (!access(parent->getPath(), AT_WRITE)) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to write to destination."); + } +} + +bool Manager::pathExists(const std::string &path) +{ + errno = 0; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(path.c_str(), &info); + if ((status != 0) && (errno != ENOENT)) { + ThrowMsg(Commons::PlatformException, + "No access to platform destination node."); + } + return 0 == status; +} + +void Manager::OnRequestReceived(const EventCopyPtr& event) +{ + Try { + INodePtr srcNode = Node::resolve(event->getSource()); + int requiredAccess; + switch (srcNode->getType()) { + case NT_DIRECTORY: + requiredAccess = AT_EXEC; + break; + case NT_FILE: + requiredAccess = AT_READ; + break; + } + if (!access(srcNode->getPath(), requiredAccess)) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to copy source node."); + } + + IPathPtr src = event->getSource(); + IPathPtr dest = event->getDestination(); + + checkPaths(src, dest); + + std::string realSrc = src->getFullPath(); + std::string realDest = dest->getFullPath(); + + if (pathExists(realDest)) { + //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(event->getDestination()); + node->remove(event->getOptions()); + } + Catch(Commons::PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + event->setExceptionCode( + Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode( + Commons::ExceptionCodes::SecurityException); + } + } + //Destination is not exist. Start copy now. + copyElement(realSrc, realDest); + + event->setResult(Node::resolve(dest)); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + //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); + if (!access(srcNode->getParent()->getPath(), AT_WRITE)) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to move source node."); + } + + checkPaths(src, dest); + + bool destExists = pathExists(dest->getFullPath()); + + if (destExists && (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; + if (0 != ::rename(src->getFullPath().c_str(), + dest->getFullPath().c_str())) + { + int error = errno; + switch (error) { + case EXDEV: + { + if (destExists) { + //destination exist. Need to be removed + Try { + INodePtr node = Node::resolve( + event->getDestination()); + node->remove(event->getOptions()); + } + Catch(Commons::PlatformException) { + LogError("Exception while removing dest directory"); + event->setExceptionCode( + Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode( + Commons::ExceptionCodes::SecurityException); + } + } + + copyElement(src->getFullPath(), + dest->getFullPath()); + //remove source files + Try { + INodePtr node = Node::resolve(event->getSource()); + node->remove(event->getOptions()); + } + Catch(Commons::Exception) { + LogError("Exception: " + << _rethrown_exception.GetMessage()); + } + break; + } + default: + ThrowMsg(Commons::PlatformException, + "Error on rename: " << DPL::GetErrnoString(error)); + break; + } + } + + event->setResult(Node::resolve(dest)); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + event->setCancelAllowed(false); +} + +void Manager::OnRequestReceived(const EventRemovePtr& event) +{ + if (!event->checkCancelled()) { + Try { + INodePtr node = Node::resolve(event->getPath()); + node->remove(event->getOptions()); + } + Catch(Commons::PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + 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) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + event->setCancelAllowed(true); +} + +bool Manager::init() +{ + m_locations[LT_ROOT] = IPath::create(PATH_ROOT); + m_locations[LT_SDCARD] = IPath::create(PATH_SDCARD); + setupLocation(LT_DOWNLOADS, PATH_DOWNLOADS); + setupLocation(LT_DOCUMENTS, PATH_DOCUMENTS); + setupLocation(LT_SOUNDS, PATH_SOUNDS); + setupLocation(LT_IMAGES, PATH_IMAGES); + setupLocation(LT_VIDEOS, PATH_VIDEOS); + + return true; +} + +void Manager::setupLocation(LocationType location, + const char* path) +{ + if (!nodeExists(path)) { + try { + makePath(path, 0755); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.DumpToString()); + return; + } + } + m_locations[location] = IPath::create(path); +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Filesystem/Manager.h b/src_mobile/modules/tizen/Filesystem/Manager.h new file mode 100644 index 0000000..fa59e3d --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Manager.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_MANAGER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include "Node.h" +#include "Path.h" + +namespace WrtDeviceApis { +namespace Filesystem { +class Manager : public Api::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); + + public: + Manager(); + ~Manager(); + + Api::IPathPtr getBasePath() const; + + Api::IPathPtr getLocationPath(Api::LocationType type) const; + + Api::LocationPaths getLocationPaths() const; + + Api::LocationTypes getLocations() const; + + void getNode(const Api::EventResolvePtr& event); + + std::size_t getMaxPathLength() const; + + void copy(const Api::EventCopyPtr& event); + + void move(const Api::EventMovePtr& event); + + void remove(const Api::EventRemovePtr& event); + + void find(const Api::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 Api::IPathPtr& path, + const Api::FiltersMap& filter, + Api::NodeList& result, + const Api::EventFindPtr& event = Api::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 Api::IPathPtr& path, + int accessType) const; + + void addOpenedNode(const Api::INodePtr& node); + void removeOpenedNode(const Api::INodePtr& node); + bool checkIfOpened(const Api::IPathPtr& path) const; + + protected: + bool matchFilters(const std::string& name, + const struct stat& info, + const Api::FiltersMap& filter); + + void OnRequestReceived(const Api::EventResolvePtr& event); + void OnRequestReceived(const Api::EventCopyPtr& event); + void OnRequestReceived(const Api::EventMovePtr& event); + void OnRequestReceived(const Api::EventRemovePtr& event); + void OnRequestReceived(const Api::EventFindPtr& event); + + private: + typedef std::map Locations; + + private: + /** + * Initializes statics of Manager class. + * Used only internally. + * @return True on success, false otherwsie. + */ + static bool init(); + + static void setupLocation(Api::LocationType location, + const char* path); + + void copyElement(const std::string &src, + const std::string &dest, + bool recursive = true) const; + + /** + * Check two paths to copy/move. Checks if they are not the same and + * required permissions. + * @param src + * @param dest + */ + void checkPaths(Api::IPathPtr &src, Api::IPathPtr &dest); + bool pathExists(const std::string &path); + + private: + static Locations m_locations; ///< Paths to default locations. + static const std::size_t m_maxPathLength; ///< Maximum path length. + static Api::NodeList m_openedNodes; ///< List of nodes that has opened + // streams. +}; +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_MANAGER_H_ diff --git a/src_mobile/modules/tizen/Filesystem/Node.cpp b/src_mobile/modules/tizen/Filesystem/Node.cpp new file mode 100644 index 0000000..221285c --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Node.cpp @@ -0,0 +1,608 @@ +/* + * 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 "Node.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Manager.h" +#include "NodeFilterMatcher.h" + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +INodePtr Node::resolve(const IPathPtr& path) +{ + struct stat info; + if (lstat(path->getFullPath().c_str(), &info) != 0) { + LogError("File: " << path->getFullPath().c_str()); + ThrowMsg(Commons::PlatformException, + "Node does not exist or access denied."); + } + + if (!S_ISDIR(info.st_mode) && !S_ISREG(info.st_mode)) { + ThrowMsg(Commons::PlatformException, + "Platform node is of unsupported type."); + } + + NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; + NodePtr result(new Node(path, type)); + return DPL::StaticPointerCast(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; + int return_code; + struct dirent entry; + struct dirent *entry_result; + for (return_code = readdir_r(dir, &entry, &entry_result); + entry_result != NULL && return_code == 0; + return_code = readdir_r(dir, &entry, &entry_result)) { + if (!strncmp(entry.d_name, ".", 1) || + !strncmp(entry.d_name, "..", 2)) + { + continue; + } + result.push_back(entry.d_name); + } + if (return_code != 0 || 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; + int return_code; + struct dirent entry; + struct dirent *entry_result; + for (return_code = readdir_r(dir, &entry, &entry_result); + entry_result != NULL && return_code == 0; + return_code = readdir_r(dir, &entry, &entry_result)) { + if (!strncmp(entry.d_name, ".", 1) || + !strncmp(entry.d_name, "..", 2)) + { + continue; + } + Try { + Assert(m_path); + 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(Commons::PlatformException) {} + } + + if (return_code != 0 || 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) +{ + LogDebug("ENTER"); + EventRequestReceiver::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."); + } + + Assert(m_path); + Assert(path); + 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(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( + SharedFromThis())); + return DPL::StaticPointerCast(stream); +} + +void Node::open(const EventOpenPtr& event) +{ + LogDebug("ENTER"); + EventRequestReceiver::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; + } +} + +std::size_t 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) { + Assert(*it); + Assert(m_path); + 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) +{ + LogDebug("ENTER"); + EventRequestReceiver::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( + 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) || ((status != 0) && (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) + { + LogError("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 */) +{ + LogDebug("ENTER"); + createAsFileInternal(path); + return new Node(path, NT_FILE); +} + +void Node::createAsFileInternal(const IPathPtr& path) +{ + LogDebug("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) +{ + Assert(path); + if (recursive) { + FTS *fts; + FTSENT *ftsent; + int error = 0; + std::string pth = path->getFullPath(); + char * const paths[] = { const_cast(pth.c_str()), NULL }; + + if ((fts = + fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) + { + //ERROR + error = errno; + LogError(__PRETTY_FUNCTION__ << ": fts_open on " + << pth + << " failed with error: " + << strerror(error)); + ThrowMsg(Commons::PlatformException, "Failed to traverse Node"); + } + + while ((ftsent = fts_read(fts)) != NULL) { + switch (ftsent->fts_info) { + case FTS_D: + //directory in preorder - do nothing + break; + case FTS_DP: + //directory in postorder - remove + errno = 0; + if (rmdir(ftsent->fts_accpath) != 0) { + if (errno == EEXIST) { + ThrowMsg(Commons::PlatformException, + "Node has child nodes."); + } + ThrowMsg(Commons::PlatformException, + "Error while removing platform node."); + } + break; + case FTS_DC: + case FTS_F: + case FTS_NSOK: + case FTS_SL: + case FTS_SLNONE: + case FTS_DEFAULT: + { + //regular files and other objects that can safely be removed + IPathPtr file_path = IPath::create(ftsent->fts_path); + removeAsFile(file_path); + break; + } + case FTS_NS: + case FTS_DOT: + case FTS_DNR: + case FTS_ERR: + default: + LogWarning(__PRETTY_FUNCTION__ + << ": traversal failed with error: " + << strerror(ftsent->fts_errno)); + break; + } + } + + if (fts_close(fts) == -1) { + error = errno; + LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: " + << strerror(error)); + } + } else { + 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::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } +} + +void Node::OnRequestReceived(const EventOpenPtr& event) +{ + if (!event->checkCancelled()) { + try { + IStreamPtr result = open(event->getMode()); + event->setResult(result); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + //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()); + LogDebug("LEAVIN GRACEFULLY"); + } + Catch(Commons::PlatformException) { + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + //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(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(); +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Filesystem/Node.h b/src_mobile/modules/tizen/Filesystem/Node.h new file mode 100644 index 0000000..de95317 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Node.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_NODE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_NODE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "Path.h" +#include "Stream.h" + +namespace WrtDeviceApis { +namespace Filesystem { +class Node : + public Api::INode, + public DPL::EnableSharedFromThis +{ + public: + static Api::INodePtr resolve(const Api::IPathPtr& path); + + public: + Api::IPathPtr getPath() const; + Api::NodeType getType() const; + int getPermissions() const; + void setPermissions(int perms); + std::size_t getSize() const; + std::time_t getCreated() const; + std::time_t getModified() const; + Api::INodePtr getParent() const; + int getMode() const; + + Api::INodePtr getChild(const Api::IPathPtr& path); + NameList getChildNames() const; + Api::NodeList getChildNodes( + const Api::NodeFilterPtr& filter = Api::NodeFilterPtr()) const; + void getChildNodes(const Api::EventListNodesPtr& event); + Api::INodePtr createChild(const Api::IPathPtr & path, + Api::NodeType, + int options); + Api::IStreamPtr open(int mode); + void open(const Api::EventOpenPtr& event); + void remove(int options); + void read(const Api::EventReadTextPtr& event); + + void onStreamClose(const StreamPtr& stream); + + private: + typedef std::set StreamList; + + private: + static bool exists(const Api::IPathPtr& path); + static struct stat stat(const Api::IPathPtr& path); + + private: + Node(const Api::IPathPtr& path, Api::NodeType type); + + Node* createAsFile(const Api::IPathPtr& path, + int options); + void createAsFileInternal(const Api::IPathPtr& path); + + Node* createAsDirectory(const Api::IPathPtr& path, + int options); + void createAsDirectoryInternal(const Api::IPathPtr& path); + + void removeAsFile(const Api::IPathPtr& path); + void removeAsDirectory(const Api::IPathPtr& path, + bool recursive); + + void OnRequestReceived(const Api::EventListNodesPtr& event); + void OnRequestReceived(const Api::EventOpenPtr& event); + + void OnRequestReceived(const Api::EventReadTextPtr& event); + std::string readText(); + + std::string toUri(int widgetId) const; + + private: + Api::IPathPtr m_path; + Api::NodeType m_type; + int m_perms; + StreamList m_openStreams; + mutable DPL::Mutex m_openStreamsMutex; +}; + +typedef DPL::SharedPtr NodePtr; +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_NODE_H_ */ diff --git a/src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.cpp b/src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.cpp new file mode 100644 index 0000000..d85f4f0 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "NodeFilterMatcher.h" + +#include + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +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()) { + return pcrecpp::RE(*filter).PartialMatch(value); + } + return true; +} + +template +bool NodeFilterMatcher::matchRange(const Type& value, + const DPL::Optional& min, + const DPL::Optional& max) +{ + if ((!min.IsNull() && (value < *min)) || + (!max.IsNull() && (value > *max))) + { + return false; + } + return true; +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.h b/src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.h new file mode 100644 index 0000000..e300058 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/NodeFilterMatcher.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +class NodeFilterMatcher +{ + public: + static bool match(const Api::INodePtr& value, + const Api::NodeFilterPtr& filter); + + private: + static bool matchString(const std::string& value, + const Api::OptionalString& filter); + + template + static bool matchRange(const Type& value, + const DPL::Optional& min, + const DPL::Optional& max); + + private: + NodeFilterMatcher(); +}; +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ diff --git a/src_mobile/modules/tizen/Filesystem/Path.cpp b/src_mobile/modules/tizen/Filesystem/Path.cpp new file mode 100644 index 0000000..9aa1197 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Path.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Path.h" + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +const Path::SeparatorType Path::m_pathSeparator = '/'; + +IPathPtr Path::create(const std::string& path) +{ + DPL::SharedPtr result(new Path()); + result->reset(path); + return DPL::StaticPointerCast(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(SharedFromThis()); +} + +IPathPtr Path::append(const IPathPtr& path) +{ + reset(m_fullPath + m_pathSeparator + path->getFullPath()); + return DPL::StaticPointerCast(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)) { + ThrowMsg(Commons::InvalidArgumentException, + "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 +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Filesystem/Path.h b/src_mobile/modules/tizen/Filesystem/Path.h new file mode 100644 index 0000000..6c7b314 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Path.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_PATH_H_ +#define WRTDEVICEAPIS_FILESYSTEM_PATH_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +class Path : public Api::IPath, + public DPL::EnableSharedFromThis +{ + public: + static Api::IPathPtr create(const std::string& path); + static Api::IPath::SeparatorType getSeparator(); + + public: + std::string getFullPath() const; + std::string getPath() const; + std::string getName() const; + Api::IPathPtr append(const std::string& path); + Api::IPathPtr append(const Api::IPathPtr& path); + bool isAbsolute() const; + Api::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 +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_PATH_H_ */ diff --git a/src_mobile/modules/tizen/Filesystem/Stream.cpp b/src_mobile/modules/tizen/Filesystem/Stream.cpp new file mode 100644 index 0000000..f63d7c4 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Stream.cpp @@ -0,0 +1,302 @@ +/* + * 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 "Stream.h" +#include +#include +#include +#include +#include +#include "Manager.h" +#include "Node.h" + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +Stream::Stream(const NodePtr& parent, + int mode) : + m_parent(parent), + m_mode(mode) +{ + Assert(m_parent && "Stream needs to have parent."); + + 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); +} + +char* Stream::getChars(std::size_t num) +{ + checkForReading(); + + std::size_t maxChars = num + 1; + DPL::ScopedArray result; + Try { + result.Reset(new char[maxChars]); + } + Catch(std::bad_alloc) { + ThrowMsg(Commons::PlatformException, "Couldn't allocate output buffer."); + } + if (m_stream.get(result.Get(), maxChars).bad()) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return result.Release(); +} + +unsigned char* Stream::getBytes(std::size_t num) +{ + checkForReading(); + + DPL::ScopedArray 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(static_cast(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(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(Commons::PlatformException, "Could not set position."); + } +} + +long Stream::getSize() const +{ + std::fstream::streampos pos = m_stream.tellg(); + if (pos == -1) { + return -1; + } + + if (!m_stream.seekg(0, std::_S_end)) { + return -1; + } + + long result = m_stream.tellg(); + m_stream.seekg(pos, std::_S_beg); + + return (result == -1 ? result : result + 1); +} + +template +IStreamPtr Stream::write_(T arg) +{ + checkForWriting(); + + if (!(m_stream << arg)) { + LogError("Error while writing to the stream."); + ThrowMsg(Commons::PlatformException, + "Error while writing to the stream."); + } + m_stream.flush(); + + return DPL::StaticPointerCast(SharedFromThis()); +} + +template +IStreamPtr Stream::read_(T& arg) +{ + checkForReading(); + + if (!(m_stream >> arg)) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return DPL::StaticPointerCast(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()) { + LogError("Stream is closed."); + ThrowMsg(Commons::PlatformException, "Stream is closed."); + } + + if (!isWriteable()) { + LogError("Stream is not writeable."); + ThrowMsg(Commons::PlatformException, "Stream is not writeable."); + } +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Filesystem/Stream.h b/src_mobile/modules/tizen/Filesystem/Stream.h new file mode 100644 index 0000000..777168f --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Stream.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_STREAM_H_ +#define WRTDEVICEAPIS_FILESYSTEM_STREAM_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +class Node; +typedef DPL::SharedPtr NodePtr; + +class Stream : + public Api::IStream, + public DPL::EnableSharedFromThis +{ + friend class Node; + + public: + ~Stream(); + + Api::IStreamPtr write(bool arg); + Api::IStreamPtr write(unsigned char arg); + Api::IStreamPtr write(char arg); + Api::IStreamPtr write(int arg); + Api::IStreamPtr write(double arg); + Api::IStreamPtr write(const std::string& arg); + + Api::IStreamPtr read(bool& arg); + Api::IStreamPtr read(unsigned char& arg); + Api::IStreamPtr read(char& arg); + Api::IStreamPtr read(int& arg); + Api::IStreamPtr read(double& arg); + Api::IStreamPtr read(std::string& arg); + + /** + * @throw PlatformException If unable to read from the stream. + */ + unsigned char* getBytes(std::size_t num); + + std::size_t getCount() const; + + /** + * @throw PlatformException If unable to read from the stream. + */ + 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; + + long getSize() const; + + private: + template + Api::IStreamPtr read_(T& arg); + template + Api::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; +}; + +typedef DPL::SharedPtr StreamPtr; +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_STREAM_H_ */ diff --git a/src_mobile/modules/tizen/Filesystem/Utils.cpp b/src_mobile/modules/tizen/Filesystem/Utils.cpp new file mode 100644 index 0000000..fc9cde0 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Utils.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Utils.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + */ + +#include +#include +#include +#include +#include +#include +#include "Utils.h" + +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 WrtDeviceApis { +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/src_mobile/modules/tizen/Filesystem/Utils.h b/src_mobile/modules/tizen/Filesystem/Utils.h new file mode 100644 index 0000000..2b1eeb3 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/Utils.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Utils.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_UTILS_H_ +#define WRTDEVICEAPIS_FILESYSTEM_UTILS_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +bool nodeExists(const std::string& path); + +void makePath(const std::string& path, mode_t mode); +} +} + +#endif diff --git a/src_mobile/modules/tizen/Filesystem/config.cmake b/src_mobile/modules/tizen/Filesystem/config.cmake new file mode 100644 index 0000000..ed22f05 --- /dev/null +++ b/src_mobile/modules/tizen/Filesystem/config.cmake @@ -0,0 +1,26 @@ +get_current_path() + +pkg_search_module(pcrecpp REQUIRED libpcrecpp + ecore REQUIRED ecore-1) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_FILESYSTEM + ${pcrecpp_INCLUDE_DIRS} + ${ecore_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_FILESYSTEM + ${pcrecpp_LIBRARIES} + ${ecore_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_FILESYSTEM + ${CURRENT_PATH}/Manager.cpp + ${CURRENT_PATH}/Node.cpp + ${CURRENT_PATH}/Path.cpp + ${CURRENT_PATH}/Stream.cpp + ${CURRENT_PATH}/NodeFilterMatcher.cpp + ${CURRENT_PATH}/Utils.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/tizen/Networking/Connection.cpp b/src_mobile/modules/tizen/Networking/Connection.cpp new file mode 100644 index 0000000..3e544c0 --- /dev/null +++ b/src_mobile/modules/tizen/Networking/Connection.cpp @@ -0,0 +1,25 @@ +/* + * 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 "Connection.h" + +namespace WrtDeviceApis { +namespace Networking { +std::string Connection::getName() const +{ + return m_name; +} +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Networking/Connection.h b/src_mobile/modules/tizen/Networking/Connection.h new file mode 100644 index 0000000..04bb4a5 --- /dev/null +++ b/src_mobile/modules/tizen/Networking/Connection.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_CONNECTION_H_ +#define WRTDEVICEAPIS_NETWORKING_CONNECTION_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Networking { +/* TODO */ +class Connection : public Api::IConnection +{ + public: + std::string getName() const; + + private: + std::string m_name; +}; +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_CONNECTION_H_ diff --git a/src_mobile/modules/tizen/Networking/EthernetAdapter.cpp b/src_mobile/modules/tizen/Networking/EthernetAdapter.cpp new file mode 100644 index 0000000..e2cf447 --- /dev/null +++ b/src_mobile/modules/tizen/Networking/EthernetAdapter.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EthernetAdapter.h" + +namespace WrtDeviceApis { +namespace Networking { +EthernetAdapter::EthernetAdapter() +{} + +void EthernetAdapter::addOnConnected( + const Api::EventConnectedEmitterPtr& emitter) +{ + m_onConnected.attach(emitter); +} + +void EthernetAdapter::removeOnConnected( + Api::EventConnectedEmitter::IdType id) +{ + m_onConnected.detach(id); +} + +void EthernetAdapter::addOnDisconnected( + const Api::EventDisconnectedEmitterPtr& emitter) +{ + m_onDisconnected.attach(emitter); +} + +void EthernetAdapter::removeOnDisconnected( + Api::EventDisconnectedEmitter::IdType id) +{ + m_onDisconnected.detach(id); +} + +Api::IAdapter::Type EthernetAdapter::getAdapterType() const +{ + return Api::IAdapter::T_ETHERNET; +} +} // Networking +} // WrtDeviceApis + diff --git a/src_mobile/modules/tizen/Networking/EthernetAdapter.h b/src_mobile/modules/tizen/Networking/EthernetAdapter.h new file mode 100644 index 0000000..6193531 --- /dev/null +++ b/src_mobile/modules/tizen/Networking/EthernetAdapter.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_ETHERNETADAPTER_H_ +#define WRTDEVICEAPIS_NETWORKING_ETHERNETADAPTER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Networking { +class Manager; + +class EthernetAdapter : public Api::IAdapter +{ + friend class Manager; + + public: + bool isConnected() const /* TODO */ + { + return false; + } + + // Api::Networking::IConnectionPtr getConnection() const { /* TODO */ } + + void addOnConnected( + const Api::EventConnectedEmitterPtr& emitter); + + void removeOnConnected(Api::EventConnectedEmitter::IdType id); + + void addOnDisconnected( + const Api::EventDisconnectedEmitterPtr& emitter); + + void removeOnDisconnected( + Api::EventDisconnectedEmitter::IdType id); + + Api::IAdapter::Type getAdapterType() const; + + private: + EthernetAdapter(); + + private: + Commons::Emitters m_onConnected; + Commons::Emitters + m_onDisconnected; +}; +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_ETHERNETADAPTER_H_ diff --git a/src_mobile/modules/tizen/Networking/Manager.cpp b/src_mobile/modules/tizen/Networking/Manager.cpp new file mode 100644 index 0000000..8416b2c --- /dev/null +++ b/src_mobile/modules/tizen/Networking/Manager.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "Manager.h" + +//#include +//#include +//#include +//#include +//#include +#include "EthernetAdapter.h" +#include "WifiAdapter.h" + +/* TODO - commented source code will be removed */ +//namespace { +//const std::size_t SSID_MAX_LENGTH = 32; +//} // anonymous + +namespace WrtDeviceApis { +namespace Networking { +//net_event_callbacks Manager::m_netEventCallbacks = +// Manager::getNetEventCallbacks(); + +Manager& Manager::getInstance() +{ + static Manager instance; + return instance; +} + +Api::IAdapter* Manager::getAdapter(Api::IAdapter::Type /*type*/) const +{ + //TODO: to be implemented + return NULL; + // Adapters::const_iterator it = m_adapters.find(type); + // if (it == m_adapters.end()) { + // return NULL; + // } + // return it->second; +} + +void Manager::getAvailableAdapters(Api::AdaptersSet *retSet) const +{ + if (retSet) { + retSet->insert(retSet->end(), m_adapters.begin(), m_adapters.end()); + } +} + +//Api::Connections Manager::getConnections() const { +// return m_connections; +//} +// +//void Manager::wlanCallback(const wlan_event_type_t* event, +// void* userData, +// void* data) +//{ +// LogDebug("--| ENTER"); +// LogDebug("Event: " << *event); +//} +// +//void Manager::onNetConnectionOpen(const NetErr_t error, +// const NetDevInfo_t* device, +// int transportErrorCode, +// void *userData) +//{ +// LogDebug("--| ENTER"); +// +//} +// +//void Manager::onNetConnectionClose(const NetErr_t error, +// int transportErrorCode, +// void *userData) +//{ LogDebug("--| ENTER"); } +// +//void Manager::onNetConnectionKill(const NetErr_t error, +// int transportErrorCode, +// void *userData) +//{ LogDebug("--| ENTER"); } +// +//void Manager::onNetStatusChange(NetStatusInfo_t* status, void *userData) { +// LogDebug("--| ENTER"); +// LogDebug("Type: " << status->transportType << ", status: " << +// status->WiFiStatus); +//} + +Manager::Manager() +{ + setupAdapters(); +} + +Manager::~Manager() +{ + removeAdapters(); +} + +void Manager::setupAdapters() +{ + //TODO: to be implemented + // Api::IAdapter* adapter = NULL; + // + // adapter = new EthernetAdapter(); + // m_adapters.insert(Adapters::value_type(Api::IAdapter::T_ETHERNET, + // adapter)); + // + // adapter = new WifiAdapter(); + // m_adapters.insert(Adapters::value_type(Api::IAdapter::T_WIFI, adapter)); +} + +void Manager::removeAdapters() +{ + //TODO: to be implemented + // Adapters::iterator it = m_adapters.begin(); + // for (; it != m_adapters.end(); ++it) { + // delete it->second; + // } + // m_adapters.clear(); +} + +//void Manager::attachListeners() { +// int error = 0; +// +// if ((error = net_register_client(&m_netEventCallbacks, this)) != +// NET_ERR_NONE) { +// LogError("Could not register to datanetworking module (" << error << +// ")."); +// } +// +// if ((error = wlan_client_register(wlanCallback, this)) != WLAN_ERR_NONE) { +// LogError("Could not register to wifi module (" << error << ")."); +// } +//} +// +//void Manager::detachListeners() { +// int error = 0; +// +// if ((error = net_deregister_client()) != NET_ERR_NONE) { +// LogError("Could not deregister from datanetworking module (" << error << +// ")."); +// } +// +// if ((error = wlan_client_deregister()) != WLAN_ERR_NONE) { +// LogError("Could not deregister from wifi module (" << error << ")."); +// } +//} + +//void Manager::initConnections() { +// int error; +// int profile = 0; +// char ssid[SSID_MAX_LENGTH + 1] = {0}; +// if ((error = wlan_client_get_connected_ap_info(&profile, ssid)) == +// WLAN_ERR_NONE) { +// Adapter* connection = new Adapter(); +// connection->setType(Api::IAdapter::T_WIFI); +// connection->setName(ssid); +// m_connections.push_back(connection); +// } +// else { +// LogError("Could not get wlan connection info (" << error << ")."); +// } +//} +// +//void Manager::clearConnections() { +// Api::Connections::iterator it = m_connections.begin(); +// for (; it != m_connections.end(); ++it) { +// delete *it; +// } +//} +// +//net_event_callbacks Manager::getNetEventCallbacks() { +// net_event_callbacks result = {0}; +// result.on_open_rsp = Manager::onNetConnectionOpen; +// result.on_close_rsp = Manager::onNetConnectionClose; +// result.on_kill_rsp = Manager::onNetConnectionKill; +// result.on_net_status = Manager::onNetStatusChange; +// return result; +//} +} // Networking +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/Networking/Manager.h b/src_mobile/modules/tizen/Networking/Manager.h new file mode 100644 index 0000000..0df9a1a --- /dev/null +++ b/src_mobile/modules/tizen/Networking/Manager.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_MANAGER_H_ +#define WRTDEVICEAPIS_NETWORKING_MANAGER_H_ + +#include +//extern "C" { +// #include +//} +//#include +#include + +namespace WrtDeviceApis { +namespace Networking { +/* TODO - commented source code will be removed */ +class Manager : public Api::IManager +{ + public: + static Manager& getInstance(); + + public: + /** + * @see Api::IManager::getAdapter() + */ + Api::IAdapter* getAdapter(Api::IAdapter::Type type) + const; + + /** + * @see Api::IManager::getAvailableAdapters + */ + virtual void getAvailableAdapters(Api::AdaptersSet *retSet) + const; + + protected: + Manager(); + virtual ~Manager(); + + /** + * Initialize adapters available on wac. + */ + void setupAdapters(); + + /** + * Cleans up adapters. + */ + void removeAdapters(); + + private: + // typedef std::map Adapters; + //private: + // static void wlanCallback(const wlan_event_type_t* event, + // void* userData, + // void* data); + // + // static void onNetConnectionOpen(const NetErr_t error, + // const NetDevInfo_t* device, + // int transportErrorCode, + // void *userData); + // + // static void onNetConnectionClose(const NetErr_t error, + // int transportErrorCode, + // void *userData); + // + // static void onNetConnectionKill(const NetErr_t error, + // int transportErrorCode, + // void *userData); + // + // static void onNetStatusChange(NetStatusInfo_t* status, void *userData); + // + // static net_event_callbacks getNetEventCallbacks(); + // + //private: + // static net_event_callbacks m_netEventCallbacks; + + private: + // DPL::Mutex m_mtx; ///< Synchronizes access to this object. + // Adapters m_adapters; ///< Adapters container. + Api::AdaptersSet m_adapters; +}; +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_MANAGER_H_ diff --git a/src_mobile/modules/tizen/Networking/WifiAdapter.cpp b/src_mobile/modules/tizen/Networking/WifiAdapter.cpp new file mode 100644 index 0000000..6ad6077 --- /dev/null +++ b/src_mobile/modules/tizen/Networking/WifiAdapter.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "WifiAdapter.h" + +namespace WrtDeviceApis { +namespace Networking { +WifiAdapter::WifiAdapter() +{} + +void WifiAdapter::addOnConnected( + const Api::EventConnectedEmitterPtr& emitter) +{ + m_onConnected.attach(emitter); +} + +void WifiAdapter::removeOnConnected( + Api::EventConnectedEmitter::IdType id) +{ + m_onConnected.detach(id); +} + +void WifiAdapter::addOnDisconnected( + const Api::EventDisconnectedEmitterPtr& emitter) +{ + m_onDisconnected.attach(emitter); +} + +void WifiAdapter::removeOnDisconnected( + Api::EventDisconnectedEmitter::IdType id) +{ + m_onDisconnected.detach(id); +} + +Api::IAdapter::Type WifiAdapter::getAdapterType() const +{ + return Api::IAdapter::T_WIFI; +} +} // Networking +} // WrtDeviceApis + diff --git a/src_mobile/modules/tizen/Networking/WifiAdapter.h b/src_mobile/modules/tizen/Networking/WifiAdapter.h new file mode 100644 index 0000000..ebb4245 --- /dev/null +++ b/src_mobile/modules/tizen/Networking/WifiAdapter.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_NETWORKING_WIFIADAPTER_H_ +#define WRTDEVICEAPIS_NETWORKING_WIFIADAPTER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Networking { +class Manager; + +class WifiAdapter : public Api::IAdapter +{ + friend class Manager; + + public: + bool isConnected() const /* TODO */ + { + return false; + } + + //Api::Networking::IConnectionPtr getConnection() const { /* TODO */ } + + void addOnConnected( + const Api::EventConnectedEmitterPtr& emitter); + + void removeOnConnected(Api::EventConnectedEmitter::IdType id); + + void addOnDisconnected( + const Api::EventDisconnectedEmitterPtr& emitter); + + void removeOnDisconnected( + Api::EventDisconnectedEmitter::IdType id); + + Api::IAdapter::Type getAdapterType() const; + + private: + WifiAdapter(); + + private: + Commons::Emitters m_onConnected; + Commons::Emitters + m_onDisconnected; +}; +} // Networking +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_NETWORKING_WIFIADAPTER_H_ diff --git a/src_mobile/modules/tizen/Networking/config.cmake b/src_mobile/modules/tizen/Networking/config.cmake new file mode 100644 index 0000000..cfae99d --- /dev/null +++ b/src_mobile/modules/tizen/Networking/config.cmake @@ -0,0 +1,20 @@ +get_current_path() + +pkg_search_module(dnet REQUIRED dnet) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_NETWORKING + ${dnet_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_NETWORKING + ${dnet_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_IMPLEMENTATION_NETWORKING + ${CURRENT_PATH}/Manager.cpp + ${CURRENT_PATH}/EthernetAdapter.cpp + ${CURRENT_PATH}/WifiAdapter.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/tizen/PluginManager/PluginManager.cpp b/src_mobile/modules/tizen/PluginManager/PluginManager.cpp new file mode 100644 index 0000000..6e2c97c --- /dev/null +++ b/src_mobile/modules/tizen/PluginManager/PluginManager.cpp @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file PluginManager.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include "PluginManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace { +const string GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; +const char* SEPARATOR = "."; +} + +namespace WrtDeviceApis { +namespace PluginManager { +PluginManager::PluginManager(int widgetHandle, + const string &objectUri, + JSObjectRef object, + JSContextRef context) : + m_widgetHandle(widgetHandle), + m_objectInstance(object), + m_objectUri(GLOBAL_OBJECT_NAME), + m_shortUri(objectUri), + m_context(context) +{ + m_objectUri.append(SEPARATOR).append(objectUri); + WrtDB::WrtDatabase::attachToThreadRO(); +} + +PluginManager::~PluginManager() +{ + ObjectList::iterator it = m_objectList.begin(); + for (; it != m_objectList.end(); ++it) { + JSValueUnprotect(m_context, it->second); + } + WrtDB::WrtDatabase::detachFromThread(); +} + +bool PluginManager::hasChild(const string &name) const +{ + const PropertyList &prop = getProperties(); + return prop.end() != find(prop.begin(), prop.end(), name); +} + +bool PluginManager::loadChild(const string &name) const +{ + _D("loading %s", name.c_str()); + string localUri = m_objectUri; + localUri.append(SEPARATOR).append(name); + + WrtDB::DbPluginHandle handle = + WrtDB::PluginDAOReadOnly::getPluginHandleForImplementedObject(localUri); + if (handle == WrtDB::INVALID_PLUGIN_HANDLE) { + _E("Plugin not found"); + return false; + } + + WrtDB::DbWidgetFeatureSet features; + WrtDB::WidgetType widgetType; + Try + { + WrtDB::WidgetDAOReadOnly dao(m_widgetHandle); + features = dao.getFeaturesList(); + widgetType = dao.getWidgetType(); + } + Catch(WrtDB::WidgetDAOReadOnly::Exception::Base) + { + // Error while reading database - widget handle may + // be invalid or some data may be missing in database + _E("Cannot get feature list"); + return false; + } + + if (widgetType == WrtDB::APP_TYPE_TIZENWEBAPP) { + JavaScriptObject jsObject = { m_objectInstance, + m_shortUri }; + return PluginLogicSingleton::Instance().loadPluginOnDemand( + handle, jsObject, const_cast(m_context)); + } + + //check does plugin with feature was requested + FOREACH(it, features) + { + if (it->pluginId == handle) { + if (it->rejected) { + _E("Feature rejected by ACE"); + continue; + } + + JavaScriptObject jsObject = { m_objectInstance, + m_shortUri }; + + return PluginLogicSingleton::Instance().loadPluginOnDemand( + handle, jsObject, + const_cast(m_context)); + } + } + _E("Plugin not loaded"); + return false; +} + +JSValueRef PluginManager::getProperty(const string &name) const +{ + _D("getProperty %s", name.c_str()); + ObjectList::const_iterator it = m_objectList.find(name); + if (it != m_objectList.end()) { + //return already set value + return it->second; + } + + if (!loadChild(name)) { + ThrowMsg(Commons::PlatformException, "Cannot load plugin"); + } + + it = m_objectList.find(name); + if (it != m_objectList.end()) { + //return set value + return it->second; + } + + ThrowMsg(Commons::PlatformException, "Cannot obtain property"); +} + +bool PluginManager::setProperty(const string &name, + JSValueRef value) +{ + _D("setProperty %s", name.c_str()); + if (m_objectList.count(name) > 0) { + JSValueUnprotect(m_context, m_objectList[name]); + } + JSValueProtect(m_context, value); + m_objectList[name] = value; + return true; +} + +bool PluginManager::deleteProperty(const string &name) +{ + if (m_objectList.count(name) > 0) { + _D("deleteProperty %s", name.c_str()); + JSValueUnprotect(m_context, m_objectList[name]); + m_objectList.erase(name); + return true; + } + return false; +} + +Api::IPluginManager::PropertyList PluginManager::getProperties() const +{ + using namespace WrtDB; + + if (!m_propertyCache.IsNull()) { + return *m_propertyCache; + } + + m_propertyCache = PropertyList(); + + WidgetDAOReadOnly dao(m_widgetHandle); + string localUri = m_objectUri + SEPARATOR; + + if (dao.getWidgetType() == APP_TYPE_TIZENWEBAPP) + { + static ImplementedObjectsList implObjectList = + PluginDAOReadOnly::getImplementedObjects(); + + FOREACH(it_implObject, implObjectList) + { + //check if implemented object stats with localUri + if (it_implObject->find(localUri) == 0) { + string property = *it_implObject; + //remove local uri that predicts property name. + property.erase(0, localUri.size()); + //check if property has its own properties. + size_t pos = property.find(SEPARATOR); + if (pos != string::npos) { + //if so then remove them. + property.erase(pos); + } + + m_propertyCache->push_back(property); + } + } + } + else + { + DbWidgetFeatureSet features; + + Try + { + features = dao.getFeaturesList(); + } + Catch(WidgetDAOReadOnly::Exception::Base) + { + _E("Cannot get feature list"); + ReThrow(Commons::PlatformException); + } + + DbWidgetFeatureSet::const_iterator feature = features.begin(); + for (; feature != features.end(); ++feature) { + ImplementedObjectsList implObjs = + PluginDAOReadOnly::getImplementedObjectsForPluginHandle( + feature->pluginId); + FOREACH(it, implObjs) { + //check if implemented object stats with localUri + if (it->find(localUri) == 0) { + string property = *it; + //remove local uri that predicts property name. + property.erase(0, localUri.size()); + //check if property has its own properties. + size_t pos = property.find(SEPARATOR); + if (pos != string::npos) { + //if so then remove them. + property.erase(pos); + } + m_propertyCache->push_back(property); + } + } + } + } + + return *m_propertyCache; +} + +void PluginManager::addPropertiesToList( + JSPropertyNameAccumulatorRef propertyNames) const +{ + PropertyList properties = getProperties(); + CommonsJavaScript::Converter converter(m_context); + FOREACH(it, properties) { + JSStringRef name = converter.toJSStringRef(*it); + JSPropertyNameAccumulatorAddName(propertyNames, name); + JSStringRelease(name); + } +} +} +} diff --git a/src_mobile/modules/tizen/PluginManager/PluginManager.h b/src_mobile/modules/tizen/PluginManager/PluginManager.h new file mode 100644 index 0000000..30b72a3 --- /dev/null +++ b/src_mobile/modules/tizen/PluginManager/PluginManager.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file PluginManager.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_PLUGINMANAGER_PLUGINMANAGER_H_ +#define WRTDEVICEAPIS_PLUGINMANAGER_PLUGINMANAGER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace PluginManager { +class PluginManager : public Api::IPluginManager +{ + public: + PluginManager(int widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context); + ~PluginManager(); + bool hasChild(const std::string &name) const; + bool loadChild(const std::string &name) const; + + JSValueRef getProperty(const std::string &name) const; + bool setProperty(const std::string &name, + JSValueRef value); + bool deleteProperty(const std::string &name); + + PropertyList getProperties() const; + void addPropertiesToList(JSPropertyNameAccumulatorRef propertyNames) const; + + private: + typedef std::map ObjectList; + + int m_widgetHandle; + JSObjectRef m_objectInstance; + std::string m_objectUri; + std::string m_shortUri; + mutable DPL::Optional m_propertyCache; + ObjectList m_objectList; + JSContextRef m_context; +}; +} +} + +#endif diff --git a/src_mobile/modules/tizen/PluginManager/config.cmake b/src_mobile/modules/tizen/PluginManager/config.cmake new file mode 100644 index 0000000..ccf3c80 --- /dev/null +++ b/src_mobile/modules/tizen/PluginManager/config.cmake @@ -0,0 +1,23 @@ +get_current_path() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +#pkg_search_module(wrt-plugin-loading REQUIRED wrt-plugin-loading) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${wrt-plugin-loading_INCLUDE_DIRS} + ${PLUGIN_LOADING_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${dpl-wrt-dao-ro_LIBRARIES} + ${wrt-plugin-loading_LIBRARIES} + ${TARGET_PLUGIN_LOADING_LIB} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${CURRENT_PATH}/PluginManager.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/tizen/Widget/Property.h b/src_mobile/modules/tizen/Widget/Property.h new file mode 100644 index 0000000..d1a19d1 --- /dev/null +++ b/src_mobile/modules/tizen/Widget/Property.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file Property.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WIDGET_PROPERTY_H_ +#define WIDGET_PROPERTY_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Widget { +template +class Property +{ + public: + explicit Property() : + m_value(), + m_valid(false) + {} + + void setValue(const T& value) + { + m_value = value; + m_valid = true; + } + + T getValue() const + { + if (!m_valid) { + Throw(Commons::PlatformException); + } + return m_value; + } + + bool isValid() const + { + return m_valid; + } + + virtual ~Property() + {} + + private: + T m_value; + bool m_valid; +}; + +typedef Property StringProperty; +typedef Property UIntProperty; +} +} +#endif diff --git a/src_mobile/modules/tizen/Widget/Widget.cpp b/src_mobile/modules/tizen/Widget/Widget.cpp new file mode 100644 index 0000000..d250452 --- /dev/null +++ b/src_mobile/modules/tizen/Widget/Widget.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file Widget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "Widget.h" +#include +#include + +namespace WrtDeviceApis { +namespace Widget { +using namespace std; +using namespace WidgetDB::Api; + +Widget::Widget() +{ + using namespace WrtDeviceApis::Commons; + m_widgetId = WrtAccessSingleton::Instance().getWidgetId(); +} + +Widget::~Widget() +{} + +string Widget::getProperty(ConfigAttribute attr) const +{ + checkWidgetId(); + + string value; + Try { + IWidgetDBPtr widgetDB = getWidgetDB(m_widgetId); + value = widgetDB->getConfigValue(attr); + } + Catch(Commons::InvalidArgumentException){ + LogError("Invalid argument exception"); + Throw(Commons::PlatformException); + } + + return value; +} + +string Widget::getAuthor() const +{ + checkWidgetId(); + + if (!m_author.isValid()) { + m_author.setValue(getProperty(ConfigAttribute::AUTHOR_NAME)); + } + return m_author.getValue(); +} + +string Widget::getAuthorEmail() const +{ + checkWidgetId(); + + if (!m_authorEmail.isValid()) { + m_authorEmail.setValue(getProperty(ConfigAttribute::AUTHOR_EMAIL)); + } + return m_authorEmail.getValue(); +} + +string Widget::getAuthorHref() const +{ + checkWidgetId(); + + if (!m_authorHref.isValid()) { + m_authorHref.setValue(getProperty(ConfigAttribute::AUTHOR_HREF)); + } + return m_authorHref.getValue(); +} + +string Widget::getDescription() const +{ + checkWidgetId(); + + if (!m_description.isValid()) { + m_description.setValue(getProperty(ConfigAttribute::DESCRIPTION)); + } + return m_description.getValue(); +} + +string Widget::getId() const +{ + checkWidgetId(); + + LogDebug("entered"); + if (!m_id.isValid()) { + m_id.setValue(getProperty(ConfigAttribute::ID)); + } + return m_id.getValue(); +} + +string Widget::getName() const +{ + checkWidgetId(); + + if (!m_name.isValid()) { + m_name.setValue(getProperty(ConfigAttribute::NAME)); + } + return m_name.getValue(); +} + +string Widget::getShortName() const +{ + checkWidgetId(); + + if (!m_shortName.isValid()) { + m_shortName.setValue(getProperty(ConfigAttribute::SHORT_NAME)); + } + return m_shortName.getValue(); +} + +string Widget::getVersion() const +{ + checkWidgetId(); + + if (!m_version.isValid()) { + m_version.setValue(getProperty(ConfigAttribute::VERSION)); + } + return m_version.getValue(); +} + +unsigned int Widget::getHeight() const +{ + checkWidgetId(); + + if (!m_height.isValid()) { + m_height.setValue(Commons::String::convertTo( + getProperty(ConfigAttribute::HEIGHT))); + } + return m_height.getValue(); +} + +unsigned int Widget::getWidth() const +{ + checkWidgetId(); + + if (!m_width.isValid()) { + m_width.setValue(Commons::String::convertTo( + getProperty(ConfigAttribute::WIDTH))); + } + return m_width.getValue(); +} + +void Widget::checkWidgetId() const +{ + if (m_widgetId < 0) { + LogError("Invalid widget id"); + Throw(Commons::InvalidArgumentException); + } + return; +} +} +} diff --git a/src_mobile/modules/tizen/Widget/Widget.h b/src_mobile/modules/tizen/Widget/Widget.h new file mode 100644 index 0000000..1dee043 --- /dev/null +++ b/src_mobile/modules/tizen/Widget/Widget.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file Widget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef PLATFORM_WIDGET_CONFIGURATION_H_ +#define PLATFORM_WIDGET_CONFIGURATION_H_ + +#include + +#include + +#include +#include +#include "Property.h" + +namespace WrtDeviceApis { +namespace Widget { +class Widget : public Api::IWidget +{ + public: + + explicit Widget(); + ~Widget(); + + virtual std::string getAuthor() const; + virtual std::string getAuthorEmail() const; + virtual std::string getAuthorHref() const; + virtual std::string getDescription() const; + virtual std::string getId() const; + virtual std::string getName() const; + virtual std::string getShortName() const; + virtual std::string getVersion() const; + virtual unsigned int getHeight() const; + virtual unsigned int getWidth() const; + + protected: + + mutable StringProperty m_author; + mutable StringProperty m_authorEmail; + mutable StringProperty m_authorHref; + mutable StringProperty m_description; + mutable StringProperty m_id; + mutable StringProperty m_name; + mutable StringProperty m_shortName; + mutable StringProperty m_version; + mutable UIntProperty m_height; + mutable UIntProperty m_width; + + private: + + std::string getProperty(WidgetDB::Api::ConfigAttribute) const; + void checkWidgetId() const; + + int m_widgetId; +}; +} +} + +#endif diff --git a/src_mobile/modules/tizen/Widget/config.cmake b/src_mobile/modules/tizen/Widget/config.cmake new file mode 100644 index 0000000..c4a3adf --- /dev/null +++ b/src_mobile/modules/tizen/Widget/config.cmake @@ -0,0 +1,6 @@ +get_current_path() + +set(SRCS_IMPLEMENTATION_WIDGET + ${CURRENT_PATH}/Widget.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/tizen/WidgetDB/WidgetDB.cpp b/src_mobile/modules/tizen/WidgetDB/WidgetDB.cpp new file mode 100644 index 0000000..08c3f42 --- /dev/null +++ b/src_mobile/modules/tizen/WidgetDB/WidgetDB.cpp @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file WidgetDB.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#include "WidgetDB.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "WidgetFeature.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +WidgetDB::WidgetDB(int widgetId) : m_widgetId(widgetId) {} + +int WidgetDB::getWidgetId() const +{ + return m_widgetId; +} + +std::string WidgetDB::getLanguage() const +{ + LogDebug("getting language"); + + WrtDB::LanguageTagList languageTags; + std::string outLanguage; + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + languageTags = dao.getLanguageTags(); + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + // get 'en' language or first from the list if 'en' does not exist + if (languageTags.size() > 1) { + FOREACH(lang, languageTags) + { + if ("en" == DPL::ToUTF8String(*lang)) { + return "en"; + } + } + } + + if (!languageTags.empty()) { + // get first language tag + outLanguage = DPL::ToUTF8String(*(languageTags.begin())); + } + return outLanguage; +} + +/*License,LicenseHref,Description,Name can be \ + * returned with incorect language*/ +std::string WidgetDB::getConfigValue(Api::ConfigAttribute attribute) const +{ + LogDebug("entered"); + std::string value; + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + WrtDB::WidgetLocalizedInfo widgetInfo = + W3CFileLocalization::getLocalizedInfo(getWidgetId()); + + std::ostringstream out; + + switch (attribute) { + case Api::ConfigAttribute::ID: { + DPL::OptionalString val = dao.getGUID(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::VERSION: { + DPL::OptionalString val = dao.getVersion(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::DESCRIPTION: { + DPL::OptionalString val = widgetInfo.description; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::LICENSE: { + DPL::OptionalString val = widgetInfo.license; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::LICENSE_HREF: { + DPL::OptionalString val = widgetInfo.licenseHref; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_NAME: { + DPL::OptionalString val = dao.getAuthorName(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_EMAIL: { + DPL::OptionalString val = dao.getAuthorEmail(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_HREF: { + DPL::OptionalString val = dao.getAuthorHref(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::NAME: { + DPL::OptionalString val = widgetInfo.name; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::SHORT_NAME: { + DPL::OptionalString val = widgetInfo.shortName; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::ACCESS_NETWORK: + value = dao.getAccessNetworkMode() ? "yes" : "no"; + break; + + case Api::ConfigAttribute::WIDTH: { + DPL::OptionalInt width = dao.getPreferredSize().width; + !width ? out << "0" : out << *width; + value = out.str(); + break; + } + + case Api::ConfigAttribute::HEIGHT: { + DPL::OptionalInt height = dao.getPreferredSize().height; + !height ? out << "0" : out << *height; + value = out.str(); + break; + } + + case Api::ConfigAttribute::INSTALL_PATH: + value = DPL::ToUTF8String(dao.getPath()); + break; + + case Api::ConfigAttribute::PUBLIC_STORAGE_PATH: + value = WrtDB::GlobalConfig::GetPublicVirtualRootPath(); + break; + + default: + LogWarning("Unknown attribute requested"); + Throw(Commons::InvalidArgumentException); + } + } + Catch(Commons::InvalidArgumentException) + { + ReThrow(Commons::InvalidArgumentException); + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + LogDebug("exit"); + + return value; +} + +std::string WidgetDB::getUserAgent() const +{ + LogDebug("Widget User_Agent data get"); + + std::string outUA("not implemented"); + return outUA; +} + +Api::InstallationStatus WidgetDB::checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const +{ + LogDebug("Checking widget ( gid(" << gid << "), name(" << name << + "), version(" << version << ")) installation status"); + + Api::InstallationStatus outStatus; + Try + { + const WrtDB::WidgetGUID w_guid = + WrtDB::WidgetGUID(DPL::FromUTF8String(gid)); + + try { + WrtDB::DbWidgetHandle widgetHandle = + WrtDB::WidgetDAOReadOnly::getHandle(w_guid); + + WrtDB::WidgetDAOReadOnly dao(widgetHandle); + DPL::OptionalString ver = dao.getVersion(); + if (!ver || version > DPL::ToUTF8String(*ver)) { + // if there is no version in DB + // or DB version is lover or equal than provided + outStatus = Api::InstallationStatus::STATUS_INSTALLED; + } else { + outStatus = Api::InstallationStatus::STATUS_LATEST; + } + } catch (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist) { + outStatus = Api::InstallationStatus::STATUS_UNINSTALLED; + } + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + return outStatus; +} + +Api::Features WidgetDB::getWidgetFeatures() const +{ + LogDebug("entered"); + WrtDB::DbWidgetFeatureSet features; + Try + { + WrtDB::WidgetDAOReadOnly doa(getWidgetId()); + features = doa.getFeaturesList(); + } + Catch(DPL::Exception) + { + // exception handle + ReThrow(Commons::SecurityException); + } + + Api::Features outFeatures; + + LogDebug("There is no exception"); + + FOREACH(it, features) + { + Api::IWidgetFeaturePtr feature( + new WidgetFeature(DPL::ToUTF8String((*it).name), + true)); // requested (WidgetFeature param) + outFeatures.push_back(feature); + } + + return outFeatures; +} + +Api::Features WidgetDB::getRegisteredFeatures() const +{ + Api::Features outRegisteredFeatures; + Try + { + // initialize with our widget features (they are required) + outRegisteredFeatures = getWidgetFeatures(); + + // searching for another features + + WrtDB::FeatureHandleList features = + WrtDB::FeatureDAOReadOnly::GetHandleList(); + + bool featureFound = false; + + // throught all features + FOREACH(registeredFeature, features) + { + WrtDB::FeatureHandle handle = *registeredFeature; + WrtDB::FeatureDAOReadOnly dao(handle); + + // check if this feature is aleready on outRegisteredFeatures list + // and if not, add it + + FOREACH(it, outRegisteredFeatures) + { + if (dao.GetName() == (*it)->getName()) { // *it = shared ptr + // this name is found on list, do not add + featureFound = true; + break; + } + } + + if (!featureFound) { + // feature is not on outRegisteredFeature so add it with + // 'required' property false + Api::IWidgetFeaturePtr newFeature(new WidgetFeature( + dao.GetName(), + false)); + + // TODO what about feature params? aren't they needed + outRegisteredFeatures.push_back(newFeature); + } + // reset the flag and check another feature + featureFound = false; + } + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + return outRegisteredFeatures; +} + +std::string WidgetDB::getWidgetInstallationPath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + std::string result(DPL::ToUTF8String(dao.getFullPath())); + result.erase(0, strlen("file://")); + std::string::size_type pos = result.size(); + std::string separator("/"); + pos = result.rfind(separator, pos); + if ((result.size() - pos) > 0 && (result.size() - pos) < 2) { + result.erase(pos, result.size()); + } + return result; + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetDB::getWidgetPersistentStoragePath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + return + WrtDB::WidgetConfig::GetWidgetPersistentStoragePath( + dao.getTizenPkgId()); + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetDB::getWidgetTemporaryStoragePath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + return + WrtDB::WidgetConfig::GetWidgetTemporaryStoragePath( + dao.getTizenPkgId()); + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} +} // WidgetDB +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/WidgetDB/WidgetDB.h b/src_mobile/modules/tizen/WidgetDB/WidgetDB.h new file mode 100644 index 0000000..b471e1a --- /dev/null +++ b/src_mobile/modules/tizen/WidgetDB/WidgetDB.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file WidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H_ +#define WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +class WidgetDB : public Api::IWidgetDB +{ + public: + + explicit WidgetDB(int widgetId); + + virtual int getWidgetId() const; + + virtual std::string getLanguage() const; + + virtual std::string getConfigValue(Api::ConfigAttribute attribute) const; + + virtual std::string getUserAgent() const; + + virtual Api::InstallationStatus checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const; + + virtual Api::Features getWidgetFeatures() const; + + virtual Api::Features getRegisteredFeatures() const; + + virtual std::string getWidgetInstallationPath() const; + + virtual std::string getWidgetPersistentStoragePath() const; + + virtual std::string getWidgetTemporaryStoragePath() const; + + private: + + int m_widgetId; +}; +} // WidgetDB +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H + diff --git a/src_mobile/modules/tizen/WidgetDB/WidgetFeature.cpp b/src_mobile/modules/tizen/WidgetDB/WidgetFeature.cpp new file mode 100644 index 0000000..aee4902 --- /dev/null +++ b/src_mobile/modules/tizen/WidgetDB/WidgetFeature.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "WidgetFeature.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +WidgetFeature::WidgetFeature(const std::string& name, + bool requested) : + m_name(name), + m_requested(requested) +{ + //LogDebug("entered"); +} + +std::string WidgetFeature::getName() const +{ + //LogDebug("entered"); + return m_name; +} + +WidgetFeature::~WidgetFeature() +{ + //LogDebug("entered"); +} + +bool WidgetFeature::isRequestedByWidget() const +{ + return m_requested; +} +} // WidgetDB +} // WrtDeviceApis diff --git a/src_mobile/modules/tizen/WidgetDB/WidgetFeature.h b/src_mobile/modules/tizen/WidgetDB/WidgetFeature.h new file mode 100644 index 0000000..d14dc69 --- /dev/null +++ b/src_mobile/modules/tizen/WidgetDB/WidgetFeature.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_H_ +#define WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +class WidgetFeature : public Api::IWidgetFeature +{ + public: + WidgetFeature(const std::string& name, + bool requested); + + std::string getName() const; + + virtual ~WidgetFeature(); + + virtual bool isRequestedByWidget() const; + + private: + std::string m_name; + bool m_requested; +}; +} // WidgetDB +} // WrtDeviceApis + +#endif diff --git a/src_mobile/modules/tizen/WidgetDB/config.cmake b/src_mobile/modules/tizen/WidgetDB/config.cmake new file mode 100644 index 0000000..6362668 --- /dev/null +++ b/src_mobile/modules/tizen/WidgetDB/config.cmake @@ -0,0 +1,22 @@ +get_current_path() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(dpl-utils-efl REQUIRED dpl-utils-efl) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_WIDGETDB + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${dpl-utils-efl_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_WIDGETDB + ${dpl-wrt-dao-ro_LDFLAGS} + ${dpl-utils-efl_LDFLAGS} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_WIDGETDB + ${CURRENT_PATH}/WidgetDB.cpp + ${CURRENT_PATH}/WidgetFeature.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/tizen/WidgetInterface/CMakeLists.txt b/src_mobile/modules/tizen/WidgetInterface/CMakeLists.txt new file mode 100644 index 0000000..883f3d1 --- /dev/null +++ b/src_mobile/modules/tizen/WidgetInterface/CMakeLists.txt @@ -0,0 +1,6 @@ + +get_current_path() + +pkg_search_module(wrt-commons-widget-interface-dao REQUIRED wrt-commons-widget-interface-dao) + +include_directories(${CURRENT_PATH}) diff --git a/src_mobile/modules/tizen/WidgetInterface/WidgetInterface.cpp b/src_mobile/modules/tizen/WidgetInterface/WidgetInterface.cpp new file mode 100644 index 0000000..cfd9c8c --- /dev/null +++ b/src_mobile/modules/tizen/WidgetInterface/WidgetInterface.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include "WidgetInterface.h" +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +using namespace WidgetInterfaceDB; + +WidgetInterfaceObject::WidgetInterfaceObject(int widgetHandle) +{ + Try + { + m_dao.reset(new WidgetInterfaceDAO(widgetHandle)); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +WidgetInterfaceObject::~WidgetInterfaceObject() +{ + m_dao.reset(); +} + +void WidgetInterfaceObject::setItem(const std::string& key, + const std::string& value, + bool readOnly) +{ + Try + { + m_dao->setItem(key, value, readOnly); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::LocalStorageValueNoModifableException) + { + LogError("Cannot delete item. Item is readonly"); + ReThrow(Commons::LocalStorageValueNoModifableException); + } +} + +void WidgetInterfaceObject::removeItem(const std::string& key) +{ + Try + { + m_dao->removeItem(key); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::LocalStorageValueNoModifableException) + { + LogError("Cannot delete item. Item is readonly"); + ReThrow(Commons::LocalStorageValueNoModifableException); + } +} + +DPL::Optional WidgetInterfaceObject::getValue( + const std::string& key) const +{ + Try + { + return m_dao->getValue(key); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +void WidgetInterfaceObject::clear(bool removeReadOnly) +{ + Try + { + m_dao->clear(removeReadOnly); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +size_t WidgetInterfaceObject::getStorageSize() const +{ + Try + { + return m_dao->getStorageSize(); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetInterfaceObject::getKeyByIndex(size_t index) const +{ + Try + { + return m_dao->getKeyByIndex(index); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::InvalidArgumentException) + { + ReThrow(Commons::InvalidArgumentException); + } +} +} diff --git a/src_mobile/modules/tizen/WidgetInterface/WidgetInterface.h b/src_mobile/modules/tizen/WidgetInterface/WidgetInterface.h new file mode 100644 index 0000000..1dacf49 --- /dev/null +++ b/src_mobile/modules/tizen/WidgetInterface/WidgetInterface.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ +#define WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +class WidgetInterfaceObject : + public LocalStorage::Api::ILocalStorage +{ + public: + WidgetInterfaceObject(int widgetHandle); + virtual ~WidgetInterfaceObject(); + + void setItem(const std::string& key, + const std::string& value, + bool readOnly); + void removeItem(const std::string& key); + DPL::Optional getValue(const std::string& key) const; + void clear(bool removeReadOnly); + size_t getStorageSize() const; + std::string getKeyByIndex(size_t index) const; + + private: + WidgetInterfaceDB::WidgetInterfaceDAOPtr m_dao; +}; +} + +#endif //WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ diff --git a/src_mobile/modules/tizen/WidgetInterface/config.cmake b/src_mobile/modules/tizen/WidgetInterface/config.cmake new file mode 100644 index 0000000..a69d23e --- /dev/null +++ b/src_mobile/modules/tizen/WidgetInterface/config.cmake @@ -0,0 +1,17 @@ + +get_current_path() + +set(WIDGET_INTERFACE_INCLUDE_DIRS + ${CURRENT_PATH} + PARENT_SCOPE +) + +SET(API_WIDGET_INTERFACE_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_WIDGET_INTERFACE + ${CURRENT_PATH}/WidgetInterface.cpp + PARENT_SCOPE +) diff --git a/src_mobile/modules/tizen/config.cmake b/src_mobile/modules/tizen/config.cmake new file mode 100644 index 0000000..82b25da --- /dev/null +++ b/src_mobile/modules/tizen/config.cmake @@ -0,0 +1,3 @@ +include_config_file(Widget) +include_config_file(StorageEvent) +include_config_file(LocalStorage) \ No newline at end of file diff --git a/src_mobile/plugin-loading/CMakeLists.txt b/src_mobile/plugin-loading/CMakeLists.txt new file mode 100644 index 0000000..fbcf48a --- /dev/null +++ b/src_mobile/plugin-loading/CMakeLists.txt @@ -0,0 +1,80 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# + +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) +pkg_search_module(dpl REQUIRED dpl-efl) +pkg_search_module(dpl-event REQUIRED dpl-event-efl) +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(webkit2 REQUIRED ewebkit2) + +set(PLUGIN_LOADING_SOURCES + ${PLUGIN_LOADING_DIRS}/plugin_logic.cpp + ${PLUGIN_LOADING_DIRS}/plugin.cpp + ${PLUGIN_LOADING_DIRS}/plugin_model.cpp + ${PLUGIN_LOADING_DIRS}/explorer.cpp + ${PLUGIN_LOADING_DIRS}/plugin_iframe_support.cpp + ${PLUGIN_LOADING_DIRS}/plugin_container_support.cpp + ${PLUGIN_LOADING_DIRS}/plugin_property_support.cpp + ${PLUGIN_LOADING_DIRS}/javascript_interface.cpp + ${PLUGIN_LOADING_DIRS}/js_page_session.cpp +) + +INCLUDE_DIRECTORIES( + ${PLUGIN_MODULE_SRC_DIR} + ${PLUGIN_LOADING_DIRS} + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGIN_LOADING_LIB} SHARED + ${PLUGIN_LOADING_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_PLUGIN_LOADING_LIB} + ${dpl_LIBRARIES} + ${dpl-event_LIBRARIES} + ${dpl-wrt-dao-ro_LIBRARIES} + ${TARGET_COMMONS} + ${TARGET_JS_OVERLAY} + wrt-plugins-tizen-service-event # static lib + wrt-plugins-softkeyboardchange-event # static lib +) + +INSTALL(TARGETS ${TARGET_PLUGIN_LOADING_LIB} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +# For wrt-plugins +INSTALL(FILES + ${PLUGIN_LOADING_DIRS}/plugin_logic.h + ${PLUGIN_LOADING_DIRS}/js_types.h + DESTINATION include/wrt-plugin-loading) diff --git a/src_mobile/plugin-loading/explorer.cpp b/src_mobile/plugin-loading/explorer.cpp new file mode 100644 index 0000000..a36aecc --- /dev/null +++ b/src_mobile/plugin-loading/explorer.cpp @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file explorer.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @author Yunchan Cho (yunchan.cho@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include +#include "explorer.h" +#include "plugin_property_support.h" + +// JS overlay +#include + +namespace { +//const char* SEPARATOR = "."; +const std::string GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; +} + +using namespace std; +using namespace PluginModule; +using namespace WrtPlugins::W3C; + +Explorer::Explorer(JSGlobalContextRef context) : + m_context(context) +{ + if (!context) { + _W("Context is NULL"); + return; + } + + m_globalObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + + //register main frame; + m_iframeSupport.registerIframe(m_globalObject); + + m_propertySupport.reset(new WindowPropertySupport(m_context)); +} + +Explorer::~Explorer() +{ +} + +JSObjectPtr Explorer::getJSObjectProperty(const std::string& propertyName, + JSObjectPtr object) +{ + return JavaScriptInterfaceSingleton::Instance().getJSObjectProperty( + m_context, object, propertyName); +} + +JSObjectPtr Explorer::getProperty( + const string& requestedProperty, + JSObjectPtr providedObject) +{ + _D("Requested Property: %s", requestedProperty.c_str()); + + if (!providedObject) { + _W("Provided object is empty"); + return JSObjectPtr(); + } + + std::string currentObjectName; + std::string currentPropertyRequested = requestedProperty; + JSObjectPtr currentObject = providedObject; + + while (true) { + auto pos = currentPropertyRequested.find("."); + if (pos == string::npos) { + return getJSObjectProperty(currentPropertyRequested, currentObject); + } + + //check if requested object has child + currentObjectName = currentPropertyRequested.substr(0, pos); + + if (currentPropertyRequested.size() <= pos + 1) { + _W("Wrong name of requested property"); + return JSObjectPtr(); + } + currentPropertyRequested = currentPropertyRequested.substr(pos + 1); + + currentObject = getJSObjectProperty(currentObjectName, currentObject); + if (!currentObject) { + _W("Failed to get property: %s", currentObjectName.c_str()); + return JSObjectPtr(); + } + } +} + +bool Explorer::registerObject(const JSObjectDeclarationPtr& declaration, + JSGlobalContextRef context) +{ + bool retValue; + + if (declaration->getParentName() == GLOBAL_OBJECT_NAME) { + retValue = register_(declaration, m_globalObject, context); + } else { //PIM support + //it should be master object name + string masterName = declaration->getParentName(); + auto pos = masterName.find("."); + if (string::npos != pos) { + _W("ParentName not allowed"); + return false; + } + auto masterObject = getJSObjectProperty(masterName, m_globalObject); + if (masterObject->getObject() == 0) { + return false; + } + retValue = registerObject(declaration, + masterName, + masterObject, + context); + } + + if (declaration->checkIframesSupported()) { + m_iframeSupport.registerDeclaration(declaration); + // m_iframeSupport.invokeCallbackForMainFrame(m_context, + // declaration, + // newObject); + } + + return retValue; +} + +bool Explorer::registerObject(const JSObjectDeclarationPtr& declaration, + const std::string& providedObjectName, + JSObjectPtr providedObject, + JSGlobalContextRef context) +{ + _D("%s <- %s", providedObjectName.c_str(), declaration->getName().c_str()); + std::string fullParentName = declaration->getParentName(); + + if (fullParentName == providedObjectName) { + _D("Provided object was matched!!"); + return register_(declaration, providedObject, context); + } + + //check if object exists in fullParentName + auto pos = fullParentName.find(providedObjectName); + if (pos == string::npos) { + _W("Object: %s should be child of: %s but you provided object: %s", + declaration->getName().c_str(), + declaration->getParentName().c_str(), + providedObjectName.c_str()); + return false; + } + + if (fullParentName.size() <= pos + providedObjectName.size() + 1) { + _W("Invalid object name"); + return false; + } + + auto currentRequesteProperty = + fullParentName.substr(pos + providedObjectName.size() + 1); + + JSObjectPtr jsObject = getProperty( + currentRequesteProperty, providedObject); + + if (!jsObject->getObject()) { + _W("Object: %s should be child of: %s. you provided object: %s but object is null", + declaration->getName().c_str(), + declaration->getParentName().c_str(), + providedObjectName.c_str()); + return false; + } + + return register_(declaration, jsObject, context); +} + +bool Explorer::register_(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parent, + JSGlobalContextRef context) +{ + _D("Registration object: %s <- %s", + declaration->getParentName().c_str(), + declaration->getName().c_str()); + Assert(parent && "parent object is NULL"); + + typedef JSObjectDeclaration::Options JO; + + JSGlobalContextRef gContext = (context == NULL) ? m_context : context; + JSObjectPtr objectInstance = JavaScriptInterfaceSingleton::Instance(). + createObject(gContext, declaration); + + JavaScriptInterfaceSingleton::Instance().setObjectProperty( + gContext, + parent, + declaration->getName(), + objectInstance); + + //notice + if (declaration->getOptions() && + (declaration->getOptions()->getIframeNotice() == + JO::IFrameNotice::AlwaysNotice)) + { + declaration->getOptions()->invokeCallback(gContext, + parent->getObject(), + objectInstance->getObject()); + } + + return true; +} + +void Explorer::registerObjectIntoIframe( + const JSObjectDeclarationPtr& declaration, + JSObjectPtr frameObject, + JSGlobalContextRef context) +{ + if (declaration->getParentName() == GLOBAL_OBJECT_NAME) { + _D("Connect to Global object of IFRAME"); + register_(declaration, frameObject, context); + return; + } + + //PIM SUPPORT + { + _D("Connect to NOT global object of IFRAME"); + //it should be master object name + string masterName = declaration->getParentName(); + auto pos = masterName.find("."); + if (string::npos != pos) { + _W("ParentName not allowed"); + return; + } + auto masterObject = getJSObjectProperty(masterName, frameObject); + if (!masterObject->getObject()) { + _W("Object not exist in frame"); + return; + } + register_(declaration, masterObject, context); + } +} + +void Explorer::loadFrame(JSGlobalContextRef context) +{ + JSObjectPtr frameObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + + if (frameObject->getObject() == m_globalObject->getObject()) { + // Main page was already loaded from constructor + _W("Main page loaded"); + return; + } + + m_iframeSupport.registerIframe(frameObject); + + auto iframeObjects = m_iframeSupport.getIframeObjects(); + + FOREACH(object, iframeObjects) + { + _D("Register object: %s", (*object)->getName().c_str()); + registerObjectIntoIframe(*object, frameObject, context); + } +} + +void Explorer::unloadFrame(JSGlobalContextRef context) +{ + JSObjectPtr frameObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + m_iframeSupport.unregisterIframe(frameObject); +} + +void Explorer::removePluginsFromIframes() +{ + if (m_iframeSupport.hasIframes()) { + JavaScriptInterfaceSingleton::Instance().removeIframes(m_context); + } +} + +void Explorer::deregisterObject(const JSObjectDeclarationPtr& declaration) +{ + if (GLOBAL_OBJECT_NAME != declaration->getParentName()) { + _W("Ignored remove property %s", declaration->getName().c_str()); + return; + } + + JavaScriptInterfaceSingleton::Instance(). + removeObjectProperty(m_context, + m_globalObject, + declaration->getName()); +} + +void Explorer::cleanIframesData() +{ + m_iframeSupport.clean(); +} + +void Explorer::callEventListeners(CustomEventType /*eventType*/, void* /*data*/) +{ +#if 0 // deprecated + using namespace WrtPlugins::Tizen; + // get iframe objects from javascript global context + JavaScriptInterface::ObjectsListPtr frameLists = + JavaScriptInterfaceSingleton::Instance().getIframesList(m_context); + + // get main frame object from javascript global context + JSObjectRef mainFrame = JSContextGetGlobalObject(m_context); + frameLists->push_back(JSObjectPtr(new JSObject(mainFrame))); + + if (eventType == ServiceCustomEvent) { + using namespace WrtDeviceApis::TizenServiceEvent::Api; + // set user data of js callback function for 'appservice' js event + ITizenServiceEventPtr event = ITizenServiceEventPtr( + new TizenServiceEvent()); + event->setScale(m_propertySupport->getScale()); + event->setBundle(m_propertySupport->getBundle()); + + // call js callback function for 'appservice' js event on each frame + FOREACH(it, *frameLists) + { + JSObjectRef frame = static_cast((*it).Get()->getObject()); + + auto eventPriv = + new JSTizenServiceEventPrivateObject(m_context, event); + JSObjectRef eventObject = + JSObjectMake(m_context, + JSTizenServiceEvent::getClassRef(), eventPriv); + + AddEventListenerSupport::CallCustomEventListenersFromIFrame( + frame, eventType, eventObject); + } + } else if (eventType == SoftKeyboardChangeCustomEvent) { + using namespace WrtDeviceApis::SoftKeyboardChangeEvent::Api; + if (!data) { + LogDebug("no ime size"); + return; + } + + // set user data of js callback function for 'softkeyboardchange' js + // event + SoftKeyboardChangeArgs* args = + static_cast(data); + ISoftKeyboardChangeEventPtr event = + ISoftKeyboardChangeEventPtr( + new SoftKeyboardChangeEvent( + args->state, + args->width, + args->height)); + LogDebug("softkeyboard event's state: " << args->state); + + // call js callback function for 'softkeyboardchange' js event on each + // frame + FOREACH(it, *frameLists) + { + JSObjectRef frame = static_cast((*it).Get()->getObject()); + + auto eventPriv = + new JSSoftKeyboardChangeEventPrivateObject(m_context, event); + JSObjectRef eventObject = + JSObjectMake( + m_context, + JSSoftKeyboardChangeEvent::getClassRef(), + eventPriv); + + AddEventListenerSupport::CallCustomEventListenersFromIFrame( + frame, eventType, eventObject); + } + } else { + LogDebug("Not supported custom event type"); + return; + } +#endif +} + +WindowPropertySupport* Explorer::getWindowPropertySupport() +{ + return m_propertySupport.get(); +} diff --git a/src_mobile/plugin-loading/explorer.h b/src_mobile/plugin-loading/explorer.h new file mode 100644 index 0000000..60d2fb6 --- /dev/null +++ b/src_mobile/plugin-loading/explorer.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file explorer.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_EXPLORER_H_ +#define WRT_SRC_PLUGIN_SERVICE_EXPLORER_H_ + +#include + +#include +#include +#include + +#include +#include +//JSGlobalContextRef +#include "javascript_interface.h" +#include "plugin_iframe_support.h" +#include "plugin_property_support.h" + +//JS overlay +#include + +using namespace PluginModule; +using namespace WrtPlugins::W3C; + +class Explorer : private DPL::Noncopyable +{ + public: + explicit Explorer(JSGlobalContextRef context); + ~Explorer(); + + //register to global frame + bool registerObject(const JSObjectDeclarationPtr& declaration, + JSGlobalContextRef context); + + bool registerObject (const JSObjectDeclarationPtr& declaration, + const std::string& parentObjectName, + JSObjectPtr parentObject, + JSGlobalContextRef context); + + void deregisterObject(const JSObjectDeclarationPtr& declaration); + + // new load/unload frame API + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void removePluginsFromIframes(); + void cleanIframesData(); + void callEventListeners(CustomEventType eventType, void* data); + + WindowPropertySupport* getWindowPropertySupport(); + + private: + + IframesSupport m_iframeSupport; + + //globalContext + JSGlobalContextRef m_context; + + //global object of main frame + JSObjectPtr m_globalObject; + + std::unique_ptr m_propertySupport; + + private: + void registerObjectIntoIframe(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parentObject, + JSGlobalContextRef context); + + bool register_(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parent, + JSGlobalContextRef context); + + JSObjectPtr getJSObjectProperty(const std::string& propertyName, + JSObjectPtr object); + + JSObjectPtr getProperty( + const std::string& requestedProperty, + JSObjectPtr providedObject); +}; + +typedef DPL::SharedPtr ExplorerPtr; +#endif diff --git a/src_mobile/plugin-loading/javascript_interface.cpp b/src_mobile/plugin-loading/javascript_interface.cpp new file mode 100644 index 0000000..5dc8f9f --- /dev/null +++ b/src_mobile/plugin-loading/javascript_interface.cpp @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_webkit.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of webkit js plugin + * accessing routines in EFL + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +IMPLEMENT_SINGLETON(JavaScriptInterface) + +#define CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, object, ret) \ + if (JSValueIsUndefined(context, object)) { \ + _E("Object %s is undefined", #object); \ + return ret; \ + } + +#define CHECK_JSOBJECT_IS_NULL_RETURN(object, ret) \ + if (!object) { \ + _E("Object %s is NULL", #object); \ + return ret; \ + } + +namespace { +/** + * Converts JSStringRef to std::string + * */ +std::string toString(const JSStringRef& arg) +{ + Assert(arg); + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(arg); + if (jsSize > 0) { + ++jsSize; + DPL::ScopedArray buffer(new char[jsSize]); + size_t written = JSStringGetUTF8CString(arg, buffer.Get(), jsSize); + if (written > jsSize) { + _E("Conversion could not be fully performed."); + return std::string(); + } + result = buffer.Get(); + } + + return result; +} + +/** + * Converts JSValueRef to std::string + * */ +std::string toString(JSContextRef ctx, JSValueRef value) +{ + Assert(ctx && value); + std::string result; + JSStringRef str = JSValueToStringCopy(ctx, value, NULL); + result = toString(str); + JSStringRelease(str); + return result; +} + +JSValueRef getProperty(JSContextRef ctx, JSValueRef value, const char* name) +{ + Assert(ctx && value && name); + JSValueRef result = NULL; + JSObjectRef obj = JSValueToObject(ctx, value, NULL); + if (obj) { + JSStringRef str = JSStringCreateWithUTF8CString(name); + result = JSObjectGetProperty(ctx, obj, str, NULL); + JSStringRelease(str); + } + return result; +} + +JSValueRef getPropertyObj(JSContextRef ctx, JSObjectRef obj, const char* name) +{ + Assert(ctx && obj && name); + JSStringRef str = JSStringCreateWithUTF8CString(name); + JSValueRef result = JSObjectGetProperty(ctx, obj, str, NULL); + JSStringRelease(str); + return result; +} + +JSObjectRef getJSGlobalObject(JSGlobalContextRef context) +{ + return JSContextGetGlobalObject(context); +} +} + +typedef JSValueRef (*JSCFunction)( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + +void JavaScriptInterface::setObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName, + const JSObjectPtr& propertyObject) +{ + _D("JSObjectSetProperty(%p, \"%s\")", context, propertyName.c_str()); + + //create name + JSStringRef name = JSStringCreateWithUTF8CString(propertyName.c_str()); + //set property + JSObjectSetProperty( + static_cast(context), + static_cast(parentObject->getObject()), name, + static_cast(propertyObject->getObject()), + kJSPropertyAttributeReadOnly, 0); + + JSStringRelease(name); +} + +void JavaScriptInterface::removeObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName) +{ + if (!context) { + //nothing to do -> no context + return; + } + _D("JSObjectDeleteProperty(%p, \"%s\")", context, propertyName.c_str()); + + JSStringRef name = JSStringCreateWithUTF8CString(propertyName.c_str()); + JSObjectDeleteProperty( + static_cast(context), + static_cast(parentObject->getObject()), name, 0); + + JSStringRelease(name); +} + +JavaScriptInterface::PropertiesList JavaScriptInterface:: + getObjectPropertiesList( + JSGlobalContextRef context, + const JSObjectPtr& object) const +{ + PropertiesList result; + JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames( + static_cast(context), + static_cast(object->getObject())); + std::size_t count = JSPropertyNameArrayGetCount(properties); + result.reserve(count); + _D("propesties count %d", count); + for (std::size_t i = 0; i < count; ++i) { + JSStringRef property = JSPropertyNameArrayGetNameAtIndex(properties, i); + result.push_back(toString(property)); + } + JSPropertyNameArrayRelease(properties); + return result; +} + +JSObjectPtr JavaScriptInterface::makeJSFunctionObject( + JSGlobalContextRef context, + const std::string &name, + js_function_impl functionImplementation) const +{ + _D("JSObjectMakeFunctionWithCallback(%p, \"%s\")", context, name.c_str()); + JSStringRef jsFunName = JSStringCreateWithUTF8CString(name.c_str()); + + JSObjectRef object = JSObjectMakeFunctionWithCallback( + context, + jsFunName, + reinterpret_cast( + functionImplementation)); + + JSStringRelease(jsFunName); + return JSObjectPtr(new JSObject(static_cast(object))); +} + +JSObjectPtr JavaScriptInterface::makeJSClassObject( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate) const +{ + _D("JSObjectMake(%p)", context); + JSObjectRef object = JSObjectMake( + context, + static_cast( + const_cast(classTemplate)), + NULL); + return JSObjectPtr(new JSObject(object)); +} + +JSObjectPtr JavaScriptInterface::makeJSObjectBasedOnInterface( + JSGlobalContextRef context, + const std::string &interfaceName) const +{ + _D("makeJSObjectBasedOnInterface(%p, \"%s\")", context, interfaceName.c_str()); + JSObjectPtr jsInterfaceObj = getJSObjectProperty(context, + getGlobalObject( + context), + interfaceName); + JSObjectRef object = JSObjectCallAsConstructor(context, + static_cast( + jsInterfaceObj-> + getObject()), 0, + NULL, + NULL); + return JSObjectPtr(new JSObject(static_cast(object))); +} + +JSObjectPtr JavaScriptInterface::makeJSInterface( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate, + JSObjectDeclaration::ConstructorCallback constructorCallback) const +{ + _D("makeJSInterface(%p)", context); + JSObjectRef object = JSObjectMakeConstructor(context, + static_cast( + const_cast< + JSObjectDeclaration:: + ClassTemplate>( + classTemplate)), + reinterpret_cast< + JSObjectCallAsConstructorCallback>( + constructorCallback) + ); + return JSObjectPtr(new JSObject(static_cast(object))); +} + +JSObjectPtr JavaScriptInterface::createObject( + JSGlobalContextRef context, + const JSObjectDeclarationPtr& + declaration) +{ + typedef JSObjectDeclaration::Options JO; + + if (declaration->getOptions()) { + switch (declaration->getOptions()->getType()) { + case JO::ClassType::Function: + return makeJSFunctionObject( + context, + declaration->getName(), + declaration->getOptions()->getFunctionImpl()); + + case JO::ClassType::Class: + if (declaration->getInterfaceName().empty()) { + return makeJSClassObject( + context, + declaration->getClassTemplate()); + } else { + return makeJSObjectBasedOnInterface( + context, + declaration->getInterfaceName()); + } + + case JO::ClassType::Interface: + return makeJSInterface( + context, + /* product class template */ + declaration->getClassTemplate(), + declaration->getConstructorCallback()); + + default: + _E("Invalid class type. Making empty JS object."); + return JSObjectPtr(new JSObject( + JSObjectMake(context, NULL, NULL))); + } + } else { + _D("No declaration options"); + return JSObjectPtr(new JSObject( + JSObjectMake( + context, + static_cast( + const_cast( + declaration->getClassTemplate())), + NULL))); + } +} + +JSObjectPtr JavaScriptInterface::getGlobalObject(JSGlobalContextRef context) +const +{ + return JSObjectPtr(new JSObject(static_cast( + JSContextGetGlobalObject(static_cast< + JSGlobalContextRef>( + context))))); +} + +JSObjectPtr JavaScriptInterface::copyObjectToIframe( + JSGlobalContextRef context, + const JSObjectPtr& iframe, + const std::string& name) +{ + _D("copyObjectToIframe(%s)", name.c_str()); + + JSGlobalContextRef jsGlobalContext = + static_cast(context); + + JSObjectRef globalObject = JSContextGetGlobalObject(jsGlobalContext); + + JSValueRef requestedObject = getPropertyObj(jsGlobalContext, + globalObject, + name.c_str()); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(jsGlobalContext, + requestedObject, + JSObjectPtr()); + + JSStringRef requestedObjectStr = + JSStringCreateWithUTF8CString(name.c_str()); + + JSObjectSetProperty(jsGlobalContext, + static_cast(iframe->getObject()), + requestedObjectStr, + requestedObject, + kJSPropertyAttributeReadOnly, + NULL); + + JSStringRelease(requestedObjectStr); + + return JSObjectPtr( + new JSObject(const_cast(requestedObject))); +} + +JavaScriptInterface::ObjectsListPtr +JavaScriptInterface::getIframesList(JSGlobalContextRef ctx) const +{ + JSGlobalContextRef context = static_cast(ctx); + JSObjectRef globalObject = JSContextGetGlobalObject(context); + ObjectsListPtr retList = getIframesList(context, globalObject); + + return retList; +} + +JavaScriptInterface::ObjectsListPtr +JavaScriptInterface::getIframesList(JSContextRef context, + JSObjectRef globalObject) const +{ + JSValueRef frames = getPropertyObj(context, globalObject, "frames"); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, frames, ObjectsListPtr()); + + JSObjectRef frames_o = JSValueToObject(context, frames, NULL); + CHECK_JSOBJECT_IS_NULL_RETURN(frames_o, ObjectsListPtr()); + + JSValueRef len = getPropertyObj(context, frames_o, "length"); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, len, ObjectsListPtr()); + + size_t count = JSValueToNumber(context, len, NULL); + _D("frames_o.length = %%d", count); + + ObjectsListPtr retList = ObjectsListPtr(new ObjectsList()); + + for (size_t i = 0; i < count; ++i) { + std::stringstream ss; + ss << i; + JSValueRef frame = getPropertyObj(context, + frames_o, + ss.str().c_str()); + if (JSValueIsUndefined(context, frame)) { + _E("Selected frame is null: frame[%d]", i); + continue; + } + JSObjectRef frame_obj = JSValueToObject(context, frame, NULL); + if (!frame_obj) { + _E("frame_obj is NULL."); + continue; + } + retList->push_back(JSObjectPtr(new JSObject(frame_obj))); + ObjectsListPtr childList = getIframesList(context, frame_obj); + + retList->merge(*childList); + _D("Frame Value Pointer: %p", frame); + _D("Frame Object Pointer: %p", frame_obj); + } + + return retList; +} + +JSObjectPtr JavaScriptInterface::getJSObjectProperty(JSGlobalContextRef ctx, + const JSObjectPtr& frame, + const std::string& name) +const +{ + _D("makeJSObjectBasedOnInterface(%p, \"%s\")", ctx, name.c_str()); + JSObjectRef frame_js = static_cast(frame->getObject()); + JSValueRef property = getPropertyObj(ctx, frame_js, name.c_str()); + JSObjectRef objProp = JSValueToObject(ctx, property, NULL); + + return JSObjectPtr(new JSObject(objProp)); +} + +void JavaScriptInterface::removeIframes(JSGlobalContextRef context) +{ + const char* deleteIframesScript = + "frame_set = document.getElementsByTagName('iframe');" + "len = frame_set.length;" + "for(i=0; i< len; i++)" + " frame_set[0].parentNode.removeChild(frame_set[0]); "; + + JSGlobalContextRef ctx = static_cast(context); + + JSStringRef script_src = JSStringCreateWithUTF8CString(deleteIframesScript); + + JSEvaluateScript(ctx, script_src, 0, 0, 0, 0); + + JSStringRelease(script_src); +} + +void JavaScriptInterface::invokeGarbageCollector(JSGlobalContextRef context) +{ + LogDebug("Garbage collection"); + JSGarbageCollect(context); + JSGarbageCollect(context); + JSGarbageCollect(context); + JSGarbageCollect(context); +} diff --git a/src_mobile/plugin-loading/javascript_interface.h b/src_mobile/plugin-loading/javascript_interface.h new file mode 100644 index 0000000..c3aa171 --- /dev/null +++ b/src_mobile/plugin-loading/javascript_interface.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file JavaScriptInterface.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRT_SRC_PLUGIN_SERVICE_WEBKIT_INTERFACE_H_ +#define WRT_SRC_PLUGIN_SERVICE_WEBKIT_INTERFACE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +//forward declaration of JSConectexRef +extern "C" { +typedef const struct OpaqueJSContext* JSContextRef; +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +class JavaScriptInterface : DPL::Noncopyable +{ + public: + + typedef std::vector PropertiesList; + + typedef std::list ObjectsList; + typedef std::shared_ptr ObjectsListPtr; + + public: + JSObjectPtr getGlobalObject(JSGlobalContextRef context) const; + + // object creation + JSObjectPtr createObject(JSGlobalContextRef context, + const JSObjectDeclarationPtr& declaration); + + //properties + void setObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName, + const JSObjectPtr& propertyObject); + + void removeObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName); + + PropertiesList getObjectPropertiesList(JSGlobalContextRef context, + const JSObjectPtr& object) const; + + JSObjectPtr copyObjectToIframe(JSGlobalContextRef context, + const JSObjectPtr& iframe, + const std::string& name); + + ObjectsListPtr getIframesList(JSGlobalContextRef context) const; + + void removeIframes(JSGlobalContextRef context); + + void invokeGarbageCollector(JSGlobalContextRef context); + + JSObjectPtr getJSObjectProperty(JSGlobalContextRef ctx, + const JSObjectPtr& frame, + const std::string& name) const; + + private: + JavaScriptInterface() + {} + + JSObjectPtr makeJSFunctionObject( + JSGlobalContextRef context, + const std::string &name, + js_function_impl functionImplementation) const; + JSObjectPtr makeJSClassObject( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate) const; + JSObjectPtr makeJSObjectBasedOnInterface( + JSGlobalContextRef context, + const std::string &interfaceName) const; + JSObjectPtr makeJSInterface( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate, + JSObjectDeclaration::ConstructorCallback constructorCallback) const; + + ObjectsListPtr getIframesList(JSContextRef context, + JSObjectRef object) const; + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton JavaScriptInterfaceSingleton; + +#endif diff --git a/src_mobile/plugin-loading/js_page_session.cpp b/src_mobile/plugin-loading/js_page_session.cpp new file mode 100644 index 0000000..cec6266 --- /dev/null +++ b/src_mobile/plugin-loading/js_page_session.cpp @@ -0,0 +1,601 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_logic.cpp + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and + * feature loading routines + * @brief This code is intended to work behind view controller + */ + +#include "plugin_logic.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "explorer.h" +#include "plugin.h" +#include "plugin_model.h" +#include "javascript_interface.h" +#include "js_function_manager.h" +#include "plugin_container_support.h" + +#include "js_page_session.h" + +using namespace std; +using namespace WrtDB; +using namespace WrtPlugins::W3C; + +namespace { +const char *LIBRARY_PATH_SEPARATOR = "/"; +} + +class JSPageSession::Impl +{ + private: + typedef std::set LoadedPlugins; + typedef std::set LoadedContexts; + + private: + ///< Widget handle using this session + int m_widgetHandle; + + //view for this session + JSGlobalContextRef m_context; + + bool m_sessionStarted; + + ///< JS object explorer for this session + Explorer* m_objectExplorer; + + PluginContainerSupportPtr m_pluginsSupport; + + ///< All loaded plugins. Each one must be unloaded. Plugins means + //set of features connected with such plugin (library) + LoadedPlugins m_loadedPlugins; + + // Set of currently loaded web pages' contexts. These contexts are + // exactly matching with each frames' global context. + LoadedContexts m_loadedContexts; + + private: + PluginPtr loadLibrary(PluginModelPtr& pluginModel); + + void installStandardFunctions(); + void installRootPlugins(); + void installRequestedFeatures(); + + //returns true if success or false if failed + bool installPlugin(PluginModelPtr plugin); + bool installPluginOnDemand(PluginModelPtr plugin, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void unloadPluginsFromSession(); + + public: + Impl(const PluginContainerSupportPtr& containerSupport); + ~Impl(); + + // Widget session + void startSession(int widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(); + + void performLibrariesUnload(); + + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(CustomEventType eventType, void* data); +}; + +JSPageSession::Impl::Impl(const PluginContainerSupportPtr& support) : + m_widgetHandle(0), + m_context(NULL), + m_sessionStarted(false), + m_objectExplorer(NULL) +{ + _D("Initializing Page Session"); + m_pluginsSupport = support; +} + +JSPageSession::Impl::~Impl() +{ + if (m_sessionStarted) { + LogError("Must stop widget session before exit!"); + stopSession(); + } + + _D("Deinitializing Page Session"); +} + + void JSPageSession::Impl::installStandardFunctions() + { + _D("========== install standard Functions START =========="); + + //add standard functions + FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) { + m_objectExplorer->registerObject(*it, NULL); + } + + _D("========== install standard Functions END =========="); + } + +void JSPageSession::Impl::installRootPlugins() +{ + _D("========== install root Functions START =========="); + + PluginContainerSupport::PluginsList rootPlugins = + m_pluginsSupport->getRootPlugins(); + FOREACH(it, rootPlugins) + { + installPlugin(*it); + } + + _D("========== install root Functions END =========="); +} + +bool JSPageSession::Impl::installPlugin(PluginModelPtr plugin) +{ + Assert(plugin && "Plugin Model is NULL"); + PluginPtr library = loadLibrary(plugin); + + if (!library) { + _E("Loading library failed"); + return false; + } + + _D("Install Plugin : %s", library->GetFileName().c_str()); + + // Register new class + FOREACH(it, *(library->GetClassList())) + { + if (!m_objectExplorer->registerObject(*it, NULL)) { + _E("Object Registration failed : %s", (*it)->getName().c_str()); + } + } + return true; +} + +void JSPageSession::Impl::installRequestedFeatures() +{ + _D("========== install requested Features START =========="); + + std::list allowedFeatures = + m_pluginsSupport->getAllowedFeatures(m_widgetHandle); + + PluginContainerSupport::PluginsList allowedPlugins; + + FOREACH(feature, allowedFeatures) + { + _D("Processing feature: %s", (*feature).c_str()); + + PluginModelPtr plugin = m_pluginsSupport->getPluginForFeature(*feature); + + if (!plugin) { + _W("It didn't have plugins! : %s", (*feature).c_str()); + continue; + } + + ImplementedObjectsList implObjs = + PluginDAOReadOnly:: + getImplementedObjectsForPluginHandle(plugin->Handle.Get()); + + FOREACH(obj, implObjs) + { + _D("Processing object: %s", (*obj).c_str()); + /* This can be optimalized, but would need extra data in database. + * There should be a list of features that are allowed to be + * installed at widget start */ + if (obj->find(".") == obj->rfind(".")) { + allowedPlugins.push_back(plugin); + _D("Plugin will be added: %s", plugin->LibraryName.Get().c_str()); + break; + } + } + } + + FOREACH(plugin, allowedPlugins) + { + _D("Installation plugin: %s", (*plugin)->LibraryName.Get().c_str()); + installPlugin(*plugin); + } + + _D("========== install requested Features END =========="); +} + +bool JSPageSession::Impl::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + Assert(parentObject.instance && + !parentObject.name.empty() + && "Wrong arguments"); + + if (!m_sessionStarted) { + _W("Session not started"); + return false; + } + // //TODO here may be a bug. if plugin contains feature rejected and + // accepted + // LogDebug("Installing feature : " << widgetFeature.name); + // if (widgetFeature.rejected) { + // LogWarning("This api-feature was rejected"); + // return; + // } + // + // auto plugin = m_pluginsSupport->getPluginModelById(pluginHandle); + // if (!plugin) { + // LogError("Failed to load plugin. plugin handle: " << + // pluginHandle); + // return false; + // } + m_pluginsSupport->registerPluginModel(pluginHandle); + return installPluginOnDemand( + m_pluginsSupport->getPluginModelById(pluginHandle), + parentObject, + context); +} + +bool JSPageSession::Impl::installPluginOnDemand(PluginModelPtr plugin, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + Assert(plugin && "Plugin Model is NULL"); + PluginPtr library = loadLibrary(plugin); + + if (!library) { + _E("Loading library failed"); + return false; + } + + _D("Install Plugin %s", library->GetFileName().c_str()); + + if (!(parentObject.instance)) { + _E("NULL pointer value"); + return false; + } + + JSObjectPtr parent(new JSObject(parentObject.instance)); + + if (!parent->getObject()) { + _E("NULL pointer value"); + assert(false); + return false; + } + + FOREACH(it, *(library->GetClassList())) + { + bool installationStatus = + m_objectExplorer->registerObject(*it, + parentObject.name, + parent, + context); + + if (!installationStatus) { + _E("Object Registration failed : %s; Parent object name: %s", + (*it)->getName().c_str(), + parentObject.name.c_str()); + return false; + } + } + + _D("Plugin on demand registration completed"); + return true; +} + +void JSPageSession::Impl::setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_objectExplorer->getWindowPropertySupport() + ->setScaleToNavigatorProperty(scaleFactor); + m_objectExplorer->getWindowPropertySupport() + ->setBundleToWindowProperty(encodedBundle); + m_objectExplorer->getWindowPropertySupport() + ->setThemeToNavigatorProperty(theme); +} + +void JSPageSession::Impl::dispatchJavaScriptEvent(CustomEventType eventType, + void* data) +{ + // Check if session is already started + if (!m_sessionStarted) { + _W("Session not started!"); + return; + } + m_objectExplorer->callEventListeners(eventType, data); +} + +void JSPageSession::Impl::startSession(int widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + + // Check if corresponding session if not already created + if (m_sessionStarted) { + _W("Session already started!"); + return; + } + + // Create js object explorer object + m_objectExplorer = new Explorer(context); + + m_sessionStarted = true; + m_widgetHandle = widgetHandle; + m_loadedPlugins.clear(); + m_context = context; + + // Register standard features + installStandardFunctions(); + + WidgetDAOReadOnly dao(m_widgetHandle); + WidgetType appType = dao.getWidgetType(); + if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) { + installRootPlugins(); + } + // Register special features + installRequestedFeatures(); + + // set scale, bundle as window's property + setCustomProperties(scaleFactor, encodedBundle, theme); +} + +void JSPageSession::Impl::stopSession() +{ + if (!m_sessionStarted) { + _W("Session not started!"); + return; + } + + unloadPluginsFromSession(); + m_sessionStarted = false; +} + +void JSPageSession::Impl::unloadPluginsFromSession() +{ + m_objectExplorer->removePluginsFromIframes(); + m_objectExplorer->cleanIframesData(); + + // delete js object for overlayed js functions + FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) + { + m_objectExplorer->deregisterObject(*it); + } + + // delete js object for plugins + FOREACH(pluginIt, m_loadedPlugins) + { + _D("Unregistering plugin %s", (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnWidgetStop(m_widgetHandle); + + FOREACH(it, *((*pluginIt)->GetClassList())) { + m_objectExplorer->deregisterObject(*it); + } + } + + JavaScriptInterfaceSingleton::Instance().invokeGarbageCollector(m_context); + + m_loadedPlugins.clear(); + + delete m_objectExplorer; + m_objectExplorer = NULL; +} + +void JSPageSession::Impl::performLibrariesUnload() +{ +#if 0 + LogDebug("Perform library unload"); + + size_t unloadedLibraries = 0; + + FOREACH(pluginIt, m_loadedPlugins) + { + LogDebug("Preparing library: " << (*pluginIt)->LibraryName.Get()); + + PluginPtr plugin = (*pluginIt)->LibraryInstance.Get(); + if (!plugin) { + LogWarning("Library not loaded " << (*pluginIt)->LibraryName.Get()); + continue; + } + unloadedLibraries++; + (*pluginIt)->LibraryInstance.Set(PluginPtr()); + } + + LogDebug("unloaded " << unloadedLibraries << " unreferenced libraries!"); +#endif +} + +PluginPtr JSPageSession::Impl::loadLibrary(PluginModelPtr& pluginModel) +{ + PluginPtr pluginLib = pluginModel->LibraryInstance.Get(); + if (!pluginLib) { + std::string path = pluginModel->LibraryPath.Get() + + std::string(LIBRARY_PATH_SEPARATOR) + + pluginModel->LibraryName.Get(); + + pluginLib = Plugin::LoadFromFile(path); + + if (!pluginLib) { + _E("Loading library failed"); + } else { + pluginModel->LibraryInstance.Set(pluginLib); + + _D("On widget start"); + // This is first time for this plugin, start widget Session + pluginLib->OnWidgetStart( + m_widgetHandle); + m_loadedPlugins.insert(pluginLib); + + FOREACH(context, m_loadedContexts) + { + pluginLib->OnFrameLoad(*context); + } + } + } else { + _D("Get from LibraryInstance"); + _D("On widget start"); + // This is first time for this plugin, start widget Session + pluginLib->OnWidgetStart( + m_widgetHandle); + m_loadedPlugins.insert(pluginLib); + + FOREACH(context, m_loadedContexts) + { + pluginLib->OnFrameLoad(*context); + } + } + + return pluginLib; +} + +void JSPageSession::Impl::loadFrame(JSGlobalContextRef context) +{ + if (!m_sessionStarted) { + _W("Session NOT started!"); + return; + } + + m_loadedContexts.insert(context); + + FOREACH(pluginIt, m_loadedPlugins) + { + _D("Try to call 'OnFrameLoad' callback : %s", + (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnFrameLoad(context); + } + + m_objectExplorer->loadFrame(context); +} + +void JSPageSession::Impl::unloadFrame(JSGlobalContextRef context) +{ + if (!m_sessionStarted) { + _W("Session NOT started!"); + return; + } + + m_loadedContexts.erase(context); + + FOREACH(pluginIt, m_loadedPlugins) + { + _D("Try to call 'OnFrameUnload' callback : %s", + (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnFrameUnload(context); + } + + m_objectExplorer->unloadFrame(context); +} + +void JSPageSession::startSession(int widgetHandle, + JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme); +} + +void JSPageSession::stopSession() +{ + m_impl->stopSession(); +} + +void JSPageSession::performLibrariesUnload() +{ + m_impl->performLibrariesUnload(); +} + +bool JSPageSession::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context); +} + +void JSPageSession::setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->setCustomProperties(scaleFactor, encodedBundle, theme); +} + +void JSPageSession::dispatchJavaScriptEvent(CustomEventType eventType, + void* data) +{ + m_impl->dispatchJavaScriptEvent(eventType, data); +} + +void JSPageSession::loadFrame(JSGlobalContextRef context) +{ + m_impl->loadFrame(context); +} + +void JSPageSession::unloadFrame(JSGlobalContextRef context) +{ + m_impl->unloadFrame(context); +} + +JSPageSession::JSPageSession(const PluginContainerSupportPtr& containerSupport) + : + m_impl(new JSPageSession::Impl(containerSupport)) +{} + +JSPageSession::~JSPageSession() +{} diff --git a/src_mobile/plugin-loading/js_page_session.h b/src_mobile/plugin-loading/js_page_session.h new file mode 100644 index 0000000..3580287 --- /dev/null +++ b/src_mobile/plugin-loading/js_page_session.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_page_session.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ +#ifndef WRT_PLUGIN_JS_PAGE_SESSION_H_ +#define WRT_PLUGIN_JS_PAGE_SESSION_H_ + +#include +#include +#include +#include +#include "js_types.h" + +using namespace WrtPlugins::W3C; + +class JSPageSession +{ + public: + // Widget session + void startSession(int widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(); + + //TODO im not sure if it is needed. I think it should be hidden + void performLibrariesUnload(); + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + // reset custom window properties. (Tizen requirements) + void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(CustomEventType eventType, void* data); + + JSPageSession(const PluginContainerSupportPtr& containerSupport); + + virtual ~JSPageSession(); + + private: + class Impl; + std::unique_ptr m_impl; +}; + +typedef std::shared_ptr JSPageSessionPtr; + +#endif // PLUGIN_LOGIC_H diff --git a/src_mobile/plugin-loading/js_types.h b/src_mobile/plugin-loading/js_types.h new file mode 100644 index 0000000..076582e --- /dev/null +++ b/src_mobile/plugin-loading/js_types.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_types.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#ifndef WRT_PLUGIN_JS_TYPES_H_ +#define WRT_PLUGIN_JS_TYPES_H_ + +//forward declaration of JSConectexRef +extern "C" { +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +struct JavaScriptObject +{ + JSObjectRef instance; + std::string name; +}; + +#endif diff --git a/src_mobile/plugin-loading/plugin.cpp b/src_mobile/plugin-loading/plugin.cpp new file mode 100644 index 0000000..246a548 --- /dev/null +++ b/src_mobile/plugin-loading/plugin.cpp @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin + */ +#include "plugin.h" +#include +#include +#include + +Plugin::Plugin(const std::string &fileName, + void *libHandle, + on_widget_start_proc *apiOnWidgetStart, + on_widget_init_proc *apiOnWidgetInit, + on_widget_stop_proc *apiOnWidgetStop, + on_frame_load_proc* apiOnFrameLoad, + on_frame_unload_proc* apiOnFrameUnload, + const ClassPtrList &apiClassList) : + m_fileName(fileName), + m_libHandle(libHandle), + m_apiOnWidgetStart(apiOnWidgetStart), + m_apiOnWidgetInit(apiOnWidgetInit), + m_apiOnWidgetStop(apiOnWidgetStop), + m_apiOnFrameLoad(apiOnFrameLoad), + m_apiOnFrameUnload(apiOnFrameUnload), + m_apiClassList(apiClassList) +{} + +Plugin::~Plugin() +{ + _D("Unloading plugin library: %s", m_fileName.c_str()); + + // Unload library + if (dlclose(m_libHandle) != 0) { + _E("Cannot close plugin handle"); + } else { + _D("Library is unloaded"); + } +} + +PluginPtr Plugin::LoadFromFile(const std::string& fileName) +{ + static bool logEnable = (getenv("WRT_LOAD_PLUGINS_LOG_ENABLE") != NULL); + + _D("LoadFromFile %s", fileName.c_str()); + + void *dllHandle; + dllHandle = dlopen(fileName.c_str(), RTLD_LAZY); + + _D("dlopen() done!"); + + if (dllHandle == NULL) { + const char* error = (const char*)dlerror(); + _E("Failed to load plugin: %s. Reason: %s", + fileName.c_str(), + (error != NULL ? error : "unknown")); + PluginPtr empty; + return empty; + } + + // Load new plugin API + on_widget_start_proc *onWidgetStartProcPtr = NULL; + on_widget_stop_proc *onWidgetStopProcPtr = NULL; + on_widget_init_proc *onWidgetInitProcPtr = NULL; + on_frame_load_proc *onFrameLoadProcPtr = NULL; + on_frame_unload_proc *onFrameUnloadProcPtr = NULL; + + const js_entity_definition_t *rawClassList = NULL; + get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL; + + onWidgetStartProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_WIDGET_START_PROC_NAME)); + onWidgetInitProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_WIDGET_INIT_PROC_NAME)); + onWidgetStopProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_WIDGET_STOP_PROC_NAME)); + onFrameLoadProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_FRAME_LOAD_PROC_NAME)); + onFrameUnloadProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_FRAME_UNLOAD_PROC_NAME)); + getWidgetEntityMapProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_GET_CLASS_MAP_PROC_NAME)); + + if (getWidgetEntityMapProcPtr) { + rawClassList = (*getWidgetEntityMapProcPtr)(); + + if (logEnable) { + _D("rawClassList : %p by getWidgetClassMapProcPtr()", + rawClassList); + } + } else { + rawClassList = + static_cast(dlsym(dllHandle, + PLUGIN_CLASS_MAP_NAME)); + if (logEnable) { _D("rawClassList : %p", rawClassList); } + } + + if (NULL == onWidgetStartProcPtr || NULL == onWidgetStopProcPtr || + /*NULL == onWidgetInitProcPtr ||*/ NULL == rawClassList) + { + if (logEnable) { + _W("#####"); + _W("##### Warning: The following plugin does not support new plugin API."); + _W("##### Old plugin API is deprecated. Please update it to new API"); + _W("#####"); + _W("##### Plugin: %s has got deprecated or invalid API", fileName.c_str()); + _W("#####"); + } + + // Will not load plugin + dlclose(dllHandle); + + PluginPtr empty; + return empty; + } + + if (logEnable) { + _D("#####"); + _D("##### Plugin: %s supports new plugin API", fileName.c_str()); + _D("#####"); + _D("##### $onWidgetStartProc: %p", onWidgetStartProcPtr); + _D("##### $onWidgetInitProc: %p", onWidgetInitProcPtr); + _D("##### $onWidgetStopProc %p", onWidgetStopProcPtr); + _D("##### $onFrameLoadProc %p", onFrameLoadProcPtr); + _D("##### $onFrameUnloadProc %p", onFrameUnloadProcPtr); + _D("##### $classMap: %p", reinterpret_cast(rawClassList)); + _D("##### "); + _D("##### Class map:"); + } + + const js_entity_definition_t *rawEntityListIterator = rawClassList; + ClassPtrList classList(new Plugin::ClassList()); + + // Parse all class definitions + while (rawEntityListIterator->parent_name != NULL && + rawEntityListIterator->object_name != NULL) + { + if (logEnable) + { + // Logging + _D("#####"); + _D("##### [%s]", rawEntityListIterator->object_name); + _D("##### Interface: %s", rawEntityListIterator->interface_name); + _D("##### Parent: %s", rawEntityListIterator->parent_name); + } + + // Register class + classList->push_back(ClassPtr(new Class(rawEntityListIterator))); + + // Go to next class + ++rawEntityListIterator; + } + + // Load export table + _D("Plugin successfuly loaded"); + + // Insert to loaded modules list + + PluginPtr instance(new Plugin(fileName, + dllHandle, + onWidgetStartProcPtr, + onWidgetInitProcPtr, + onWidgetStopProcPtr, + onFrameLoadProcPtr, + onFrameUnloadProcPtr, + classList)); + + return instance; +} + +std::string Plugin::GetFileName() const +{ + return m_fileName; +} + +void Plugin::OnWidgetStart(int widgetId) +{ + if (NULL != m_apiOnWidgetStart) { + (*m_apiOnWidgetStart)(widgetId); + _D("Called!"); + } +} + +void Plugin::OnWidgetInit(feature_mapping_interface_t* mapping) +{ + Assert(NULL != mapping && "NULL mapping interface provided"); + if (NULL != m_apiOnWidgetInit) { + (*m_apiOnWidgetInit)(mapping); + _D("Called!"); + } +} + +void Plugin::OnWidgetStop(int widgetId) +{ + if (NULL != m_apiOnWidgetStop) { + (*m_apiOnWidgetStop)(widgetId); + _D("Called!"); + } +} + +void Plugin::OnFrameLoad(java_script_context_t context) +{ + if (NULL != m_apiOnFrameLoad) { + (*m_apiOnFrameLoad)(context); + _D("Called!"); + } +} + +void Plugin::OnFrameUnload(java_script_context_t context) +{ + if (NULL != m_apiOnFrameUnload) { + (*m_apiOnFrameUnload)(context); + _D("Called!"); + } +} + +const Plugin::ClassPtrList Plugin::GetClassList() const +{ + return m_apiClassList; +} diff --git a/src_mobile/plugin-loading/plugin.h b/src_mobile/plugin-loading/plugin.h new file mode 100644 index 0000000..1eb277f --- /dev/null +++ b/src_mobile/plugin-loading/plugin.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin + */ +#ifndef WRT_SRC_PLUGIN_SERVICE_PLUGIN_H_ +#define WRT_SRC_PLUGIN_SERVICE_PLUGIN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +class Plugin; +typedef DPL::SharedPtr PluginPtr; + +class Plugin : private DPL::Noncopyable +{ + public: + typedef JSObjectDeclaration Class; + typedef JSObjectDeclarationPtr ClassPtr; + typedef std::list ClassList; + typedef DPL::SharedPtr ClassPtrList; + + private: + ///< Plug-in identifier. Currently plug-in file name is used as the ID + std::string m_fileName; + + ///< Handle for the plug-in library. A plug-in is a dynamic loadable library + void* m_libHandle; + + // Plugin API + on_widget_start_proc* m_apiOnWidgetStart; + on_widget_init_proc* m_apiOnWidgetInit; + on_widget_stop_proc* m_apiOnWidgetStop; + on_frame_load_proc* m_apiOnFrameLoad; + on_frame_unload_proc* m_apiOnFrameUnload; + const ClassPtrList m_apiClassList; + + Plugin(const std::string &fileName, + void *libHandle, + on_widget_start_proc* apiOnWidgetStart, + on_widget_init_proc* apiOnWidgetInit, + on_widget_stop_proc* apiOnWidgetStop, + on_frame_load_proc* apiOnFrameLoad, + on_frame_unload_proc* apiOnFrameUnload, + const ClassPtrList &apiClassList); + + public: + virtual ~Plugin(); + + // Loading + static PluginPtr LoadFromFile(const std::string &fileName); + + // Filename + std::string GetFileName() const; + + // API + void OnWidgetStart(int widgetId); + + void OnWidgetInit(feature_mapping_interface_t *interface); + + void OnWidgetStop(int widgetId); + + void OnFrameLoad(java_script_context_t context); + + void OnFrameUnload(java_script_context_t context); + + const ClassPtrList GetClassList() const; +}; + +#endif // PLUGIN_H diff --git a/src_mobile/plugin-loading/plugin_container_support.cpp b/src_mobile/plugin-loading/plugin_container_support.cpp new file mode 100644 index 0000000..064e8a4 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_container_support.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_container_support.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#include "plugin_container_support.h" + +#include + +#include +#include +#include +#include + + using namespace WrtDB; + +#include + +PluginContainerSupport::PluginContainerSupport() : + m_initialized(false), + m_widgetHandle(0) +{ + // Reading root plugins list from so files + readRootPluginsList(); +} + +PluginContainerSupport::~PluginContainerSupport() +{ + // Remove all plugin models + m_pluginModels.clear(); + + // Remove all feature models + m_featureModels.clear(); + } + +void PluginContainerSupport::Initialize(int widgetHandle) +{ + if (isInitialized() == true && m_widgetHandle != widgetHandle) { + // re-initialize required + m_initialized = false; + + m_pluginModels.clear(); + m_featureModels.clear(); + } + + if (isInitialized() == false) { + m_initialized = true; + m_widgetHandle = widgetHandle; + + readAllowedPlugins(widgetHandle); + readRootPlugins(widgetHandle); + } +} + +std::list PluginContainerSupport::getAllowedFeatures( + int widgetHandle) const +{ + //TODO it has to return LIST NOT SET!!! + WidgetDAOReadOnly widgetDao(widgetHandle); + DbWidgetFeatureSet features = widgetDao.getFeaturesList(); + + std::list allowedFeatures; + FOREACH(it, features) { + _D("Loading api-feature: %s", DPL::ToUTF8String(it->name).c_str()); + if (it->rejected) { + _W("Api-feature was rejected by ace. (Api-feature name: %s)", + it->name.c_str()); + continue; + } + + allowedFeatures.push_back(DPL::ToUTF8String(it->name)); + } + return allowedFeatures; +} + +void PluginContainerSupport::readAllowedPlugins(int widgetHandle) +{ + std::list allowedFeatures; + auto requested = getAllowedFeatures(widgetHandle); + FOREACH(f, requested) + { + allowedFeatures.push_back(*f); + } + + FeatureData* dt = NULL; + std::map featureDataList = FeatureDAOReadOnly::GetFeatures( + allowedFeatures); + DeviceCapList deviceCapabilities = + FeatureDAOReadOnly::GetDevCapWithFeatureHandle(); + FOREACH(data, featureDataList) { + dt = &(data->second); + registerPluginModel(dt->pluginHandle); + registerFeatureModel(data->first, dt, deviceCapabilities); + } +} + +void PluginContainerSupport::readRootPlugins(int widgetHandle) +{ + WidgetDAOReadOnly dao(widgetHandle); + WidgetType appType = dao.getWidgetType(); + if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) { + FOREACH(it_rootPluginHandle, m_rootPluginsList) + { + _D("*it_rootPluginHandle: %d", *it_rootPluginHandle); + registerPluginModel(*it_rootPluginHandle); + } + } else { + _D("Not defined app type"); + } +} + +void PluginContainerSupport::registerFeatureModel( + FeatureHandle handle, + FeatureData* data, + DeviceCapList + deviceCapabilities) +{ + FeatureModelPtr model = getFeatureModel(handle); + if (model) { + _D("Model for feature: %d already created", handle); + return; + } + + _D("Creating Model for feature: %d", handle); + + model.reset(new FeatureModel(handle)); + + std::set devCapList; + auto ret = deviceCapabilities.equal_range(handle); + for (auto devCapIt = ret.first; devCapIt != ret.second; devCapIt++) { + devCapList.insert((*devCapIt).second); + } + model->SetData(data->featureName, devCapList, data->pluginHandle); + m_featureModels.insert(model); +} + +void PluginContainerSupport::registerPluginModel(DbPluginHandle handle) +{ + PluginModelPtr model = getPluginModelById(handle); + + if (model) { + _D("Model for plugin: %d already registered", handle); + return; + } + + if (PluginDAOReadOnly::INSTALLATION_COMPLETED != + PluginDAOReadOnly::getInstallationStateForHandle(handle)) + { + _W("Failed To CreateModel for handle %d", handle); + return; + } + + model.Reset(new PluginModel(handle)); + + _D("Model Created. Handle: %d, name: %s", + handle, + model->LibraryName.Get().c_str()); + + m_pluginModels.insert(model); +} + +void PluginContainerSupport::readRootPluginsList() +{ + _D("Reading root plugins list from so files..."); + m_rootPluginsList = PluginDAOReadOnly::getRootPluginHandleList(); +} + +FeatureModelPtr +PluginContainerSupport::getFeatureModel(const std::string &name) const +{ + FOREACH(iter, m_featureModels) + { + if ((*iter)->Name.Get() == name) { + return *iter; + } + } + + return FeatureModelPtr(); +} + +FeatureModelPtr +PluginContainerSupport::getFeatureModel(const FeatureHandle handle) const +{ + FOREACH(iter, m_featureModels) + { + if ((*iter)->FHandle.Get() == handle) { + return *iter; + } + } + + return FeatureModelPtr(); +} + +PluginModelPtr +PluginContainerSupport::getPluginModelById(DbPluginHandle handle) const +{ + FOREACH(pluginModel, m_pluginModels) + { + if ((*pluginModel)->Handle.Get() == handle) { + return *pluginModel; + } + } + + return PluginModelPtr(); +} + +PluginModelPtr +PluginContainerSupport::getPluginModel(const FeatureModelPtr &feature) const +{ + if (!feature) { + _D("Null Ptr for feature model"); + return PluginModelPtr(); + } else { + _D("Feature located in plugin: %d", feature->PHandle.Get()); + return getPluginModelById(feature->PHandle.Get()); + } +} + + PluginContainerSupport::PluginsList +PluginContainerSupport::getRootPlugins() const +{ + PluginsList plugins; + + FOREACH(it, m_rootPluginsList) { + PluginModelPtr plugin = getPluginModelById(*it); + if (!plugin) { + _W("PluginModel not found"); + continue; + } + + plugins.push_back(plugin); + } + + return plugins; +} + +PluginContainerSupport::PluginsList +PluginContainerSupport::getPluginsList() const +{ + PluginsList plugins; + + FOREACH(it, m_pluginModels) { + plugins.push_back(*it); + } + + return plugins; +} + +PluginModelPtr +PluginContainerSupport::getPluginForFeature(const std::string& featureName) +{ + return getPluginModel(getFeatureModel(featureName)); +} diff --git a/src_mobile/plugin-loading/plugin_container_support.h b/src_mobile/plugin-loading/plugin_container_support.h new file mode 100644 index 0000000..dbdf6c5 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_container_support.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_container_support.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ +#ifndef PLUGIN_CONTAINER_SUPPORT_H +#define PLUGIN_CONTAINER_SUPPORT_H + +#include +#include +#include + +#include +#include + +#include "plugin_model.h" + +class PluginContainerSupport +{ + public: + typedef std::list FeaturesList; + typedef std::list PluginsList; + + private: + // Standard features + typedef std::list StandardFeatureList; + + // Main feature list. Always equal to DB feature list + typedef std::set FeatureModelContainer; + + // Main plugin list. Always equal to DB plugin list + typedef std::set PluginModelsContainer; + + WrtDB::PluginHandleList m_rootPluginsList; + + PluginModelsContainer m_pluginModels; + + FeatureModelContainer m_featureModels; + + bool m_initialized; + + int m_widgetHandle; + + private: + // Reading + void readRootPluginsList(); + + // Plugin models + typedef std::multimap DeviceCapList; + void registerFeatureModel(WrtDB::FeatureHandle handle, + WrtDB::FeatureData* data, + DeviceCapList deviceCapabilities); + + WrtDB::FeatureModelPtr getFeatureModel(const std::string &name) const; + WrtDB::FeatureModelPtr getFeatureModel(WrtDB::FeatureHandle handle) const; + + PluginModelPtr getPluginModel(const WrtDB::FeatureModelPtr &feature) const; + + public: + PluginContainerSupport(); + + bool isInitialized() + { + return m_initialized; + } + bool isInitialized(int widgetHandle) + { + return (m_initialized && m_widgetHandle == widgetHandle); + } + void Initialize(int widgetHandle); + void registerPluginModel(WrtDB::DbPluginHandle handle); + std::list getAllowedFeatures(int widgetHandle) const; + void readAllowedPlugins(int widgetHandle); + void readRootPlugins(int widgetHandle); + PluginsList getRootPlugins() const; + PluginsList getPluginsList() const; + + PluginModelPtr getPluginForFeature(const std::string& featureName); + + PluginModelPtr getPluginModelById(WrtDB::DbPluginHandle handle) const; + + ~PluginContainerSupport(); +}; + +typedef std::shared_ptr PluginContainerSupportPtr; + +#endif // PLUGIN_CONTAINER_SUPPORT_H diff --git a/src_mobile/plugin-loading/plugin_iframe_support.cpp b/src_mobile/plugin-loading/plugin_iframe_support.cpp new file mode 100644 index 0000000..4e428dd --- /dev/null +++ b/src_mobile/plugin-loading/plugin_iframe_support.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_iframe_support.cpp + * @version 1.0 + * @brief + */ + +#include "plugin_iframe_support.h" + +#include +#include +#include + +void IframesSupport::registerDeclaration( + const JSObjectDeclarationPtr& declaration) +{ + _D("Registration iframes-supported plugins %s", declaration->getName().c_str()); + + if (declaration->getParentName().find('.') != std::string::npos) { + _E("The object will not be loaded to iframes"); + return; + } + m_iframesObjects.push_back(declaration); +} + +void IframesSupport::registerIframe(const JSObjectPtr& iframe) +{ + _D("LoadedIframes size: %d", m_loadedIframes.size() ); + + m_loadedIframes.insert(iframe); +} + +void IframesSupport::unregisterIframe(const JSObjectPtr& iframe) +{ + _D("LoadedIframes size: %d", m_loadedIframes.size() ); + + auto it_loaded = std::find_if(m_loadedIframes.begin(), + m_loadedIframes.end(), + std::bind2nd(EqualToJSObjectPtr(), iframe)); + //object not found, so thats the new iframe + if (it_loaded == m_loadedIframes.end()) { + _D("Nothing to unregister"); + return; + } + + m_loadedIframes.erase(it_loaded); +} + +bool IframesSupport::hasIframes() const +{ + return !m_loadedIframes.empty(); +} + +IframesSupport::DeclarationsList IframesSupport::getIframeObjects() const +{ + return m_iframesObjects; +} + +void IframesSupport::clean() +{ + m_iframesObjects.clear(); + m_loadedIframes.clear(); +} diff --git a/src_mobile/plugin-loading/plugin_iframe_support.h b/src_mobile/plugin-loading/plugin_iframe_support.h new file mode 100644 index 0000000..0c98768 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_iframe_support.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_iframe_support.h + * @version 1.0 + * @brief + */ + +#ifndef _WRTENGINE_SRC_PLUGINSERVICE_IFRAME_SUPPORT_H_ +#define _WRTENGINE_SRC_PLUGINSERVICE_IFRAME_SUPPORT_H_ + +#include +#include +#include +#include +#include "javascript_interface.h" + +class IframesSupport +{ + public: + typedef std::list DeclarationsList; + + public: + void registerDeclaration(const JSObjectDeclarationPtr& declaration); + + void registerIframe(const JSObjectPtr& iframe); + + void unregisterIframe(const JSObjectPtr& iframe); + + DeclarationsList getIframeObjects() const; + + bool hasIframes() const; + + void clean(); + + private: + std::list m_iframesObjects; + std::set m_loadedIframes; + + // used to find matching object from m_loadedIframes + struct EqualToJSObjectPtr + { + typedef JSObjectPtr first_argument_type; + typedef JSObjectPtr second_argument_type; + typedef bool result_type; + + result_type operator()(const first_argument_type &s1, + const second_argument_type &s2) const + { + return (s1->getObject() == s2->getObject()); + } + }; +}; + +#endif diff --git a/src_mobile/plugin-loading/plugin_logic.cpp b/src_mobile/plugin-loading/plugin_logic.cpp new file mode 100644 index 0000000..8458501 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_logic.cpp @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_logic.cpp + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and + * feature loading routines + * @brief This code is intended to work behind view controller + */ + +#include "plugin_logic.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "explorer.h" +#include "plugin.h" +#include "plugin_model.h" +#include "javascript_interface.h" +#include "js_function_manager.h" +#include "plugin_container_support.h" + +#include "js_page_session.h" + +using namespace std; +using namespace WrtDB; +using namespace WrtPlugins::W3C; + +namespace { +const char *LIBRARY_PATH_SEPARATOR = "/"; +} + +class PluginLogic::Impl +{ + PluginContainerSupportPtr m_pluginsSupport; + + typedef std::map PagesSessionsSet; + PagesSessionsSet m_sessions; + unsigned int m_windowHandle; + + public: + Impl(); + ~Impl(); + + // Widget session + void initSession(int widgetHandle); + void startSession(int widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(JSGlobalContextRef context); + + void performLibrariesUnload(); + + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void setCustomProperties(JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(JSGlobalContextRef ctx, + CustomEventType eventType, + void* data); + + unsigned int windowHandle() const; + void setWindowHandle(unsigned int handle); + + static bool s_sanityCheck; +}; + +IMPLEMENT_SINGLETON(PluginLogic); + +bool PluginLogic::Impl::s_sanityCheck = false; + +#define PLUGIN_LOGIC_SANITY_CHECK \ + if (!s_sanityCheck) \ + { \ + _E("Object is not available. Wrong flow occured"); \ + return; \ + } + +PluginLogic::Impl::Impl() : + m_windowHandle(0) +{ + s_sanityCheck = true; + + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + _D("Initializing Plugin Logic..."); + m_pluginsSupport = PluginContainerSupportPtr(new PluginContainerSupport()); + + // explicit call to keep singleton's lifetime until calling destructor. + JsFunctionManagerSingleton::Instance(); + JavaScriptInterfaceSingleton::Instance(); +} + +PluginLogic::Impl::~Impl() +{ + _D("called"); + + s_sanityCheck = false; + + FOREACH(it, m_sessions) + { + _W("Must stop widget session before exit!"); + it->second->stopSession(); + } +} + +void PluginLogic::initSession(int widgetHandle) +{ + m_impl->initSession(widgetHandle); +} + +void PluginLogic::startSession(int widgetHandle, + JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme); +} + +void PluginLogic::stopSession(JSGlobalContextRef context) +{ + m_impl->stopSession(context); +} + +void PluginLogic::performLibrariesUnload() +{ + _W("This function is DEPRECATED"); + // m_impl->performLibrariesUnload(); +} + +bool PluginLogic::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context); +} + +void PluginLogic::loadPluginsIntoIframes(JSGlobalContextRef /*context*/) +{ + _W("This function is DEPRECATED"); +} + +void PluginLogic::setCustomProperties(double /*scaleFactor*/, + const char* /*encodedBundle*/, + const char* /*theme*/) +{ + _W("This function is DEPRECATED"); +} + +void PluginLogic::setCustomProperties(JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->setCustomProperties(context, scaleFactor, encodedBundle, theme); +} + +void PluginLogic::dispatchJavaScriptEvent(CustomEventType /*eventType*/) +{ + _W("This function is DEPRECATED"); +} + +void PluginLogic::dispatchJavaScriptEvent(JSGlobalContextRef context, + CustomEventType eventType, + void *data) +{ + m_impl->dispatchJavaScriptEvent(context, eventType, data); +} + +void PluginLogic::loadFrame(JSGlobalContextRef context) +{ + m_impl->loadFrame(context); +} + +void PluginLogic::unloadFrame(JSGlobalContextRef context) +{ + m_impl->unloadFrame(context); +} + +unsigned int PluginLogic::windowHandle() const +{ + return m_impl->windowHandle(); +} + +void PluginLogic::setWindowHandle(unsigned int handle) +{ + m_impl->setWindowHandle(handle); +} + +PluginLogic::PluginLogic() : m_impl(new PluginLogic::Impl()) +{} + +PluginLogic::~PluginLogic() +{} + +void PluginLogic::Impl::initSession(int widgetHandle) +{ + _D(">---------------------[init session START]---------------------<"); + + m_pluginsSupport->Initialize(widgetHandle); + PluginContainerSupport::PluginsList rootPluginList = + m_pluginsSupport->getRootPlugins(); + + FOREACH(it, rootPluginList) + { + PluginModelPtr& pluginModel = *it; + PluginPtr pluginLib = pluginModel->LibraryInstance.Get(); + + if (!pluginLib) { + std::string path = pluginModel->LibraryPath.Get() + + std::string(LIBRARY_PATH_SEPARATOR) + + pluginModel->LibraryName.Get(); + + pluginLib = Plugin::LoadFromFile(path); + + if (!pluginLib) { + _W("Loading library failed"); + } else { + pluginModel->LibraryInstance.Set(pluginLib); + _D("pluginModel->LibraryInstance.Set() : %s", + pluginLib->GetFileName().c_str()); + } + } else { + _D("Already loaded"); + } + } + _D("========== init session END =========="); +} + +void PluginLogic::Impl::startSession(int widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + _D("========== start session START =========="); + + if (!m_pluginsSupport->isInitialized(widgetHandle)) { + m_pluginsSupport->Initialize(widgetHandle); + } + auto sessionIt = m_sessions.find(context); + + // Check if corresponding session if not already created + if (sessionIt != m_sessions.end()) { + _W("Session already started!"); + } else { + auto newSession = JSPageSessionPtr(new JSPageSession(m_pluginsSupport)); + newSession->startSession(widgetHandle, + context, + scaleFactor, + encodedBundle, + theme); + + m_sessions[context] = newSession; + } + _D("========== start session END =========="); +} + +void PluginLogic::Impl::stopSession(JSGlobalContextRef context) +{ + _D("========== stop session START =========="); + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + } else { + sessionIt->second->stopSession(); + m_sessions.erase(sessionIt); + } + _D("========== stop session END =========="); +} + +bool PluginLogic::Impl::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context + ) +{ + _D("========== load ondemand plugin =========="); + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + return false; + } + + return sessionIt->second->loadPluginOnDemand(pluginHandle, + parentObject, + context); +} + +void PluginLogic::Impl::loadFrame(JSGlobalContextRef context) +{ + _D("========== load frame START =========="); + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + } else { + sessionIt->second->loadFrame(context); + } + _D("========== load frame END =========="); +} + +void PluginLogic::Impl::unloadFrame(JSGlobalContextRef context) +{ + _D("========== unload frame START =========="); + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + LogWarning("Session not exist!"); + } else { + sessionIt->second->unloadFrame(context); + + // I don't know why this session should be removed here. + // session list is removed also from stopSession(). + //m_sessions.erase(sessionIt); + } + _D("========== unload frame END =========="); +} + +void PluginLogic::Impl::setCustomProperties(JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + return; + } + + sessionIt->second->setCustomProperties(scaleFactor, + encodedBundle, + theme); +} + +void PluginLogic::Impl::dispatchJavaScriptEvent(JSGlobalContextRef context, + CustomEventType eventType, + void* data) +{ + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + return; + } + + sessionIt->second->dispatchJavaScriptEvent(eventType, data); +} + +unsigned int PluginLogic::Impl::windowHandle() const +{ + if (!s_sanityCheck) { + LogError("Object is not available. Wrong flow occured"); + } + return m_windowHandle; +} + +void PluginLogic::Impl::setWindowHandle(unsigned int handle) +{ + PLUGIN_LOGIC_SANITY_CHECK + m_windowHandle = handle; +} diff --git a/src_mobile/plugin-loading/plugin_logic.h b/src_mobile/plugin-loading/plugin_logic.h new file mode 100644 index 0000000..fb965c5 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_logic.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_logic.h + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and feature + * loading routines + * @brief This code is intended to work behind view controller + */ +#ifndef PLUGIN_LOGIC_H +#define PLUGIN_LOGIC_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace WrtPlugins::W3C; + +class PluginLogic : DPL::Noncopyable +{ + public: + // Widget session + void initSession(int widgetHandle); + void startSession(int widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(JSGlobalContextRef context); + + //TODO im not sure if it is needed. I think it should be hidden + void performLibrariesUnload(); + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + WRT_PLUGINS_DEPRECATED void loadPluginsIntoIframes( + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + // reset custom window properties. (Tizen requirements) + WRT_PLUGINS_DEPRECATED void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void setCustomProperties(JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + WRT_PLUGINS_DEPRECATED void dispatchJavaScriptEvent( + CustomEventType eventType); + + void dispatchJavaScriptEvent(JSGlobalContextRef ctx, + CustomEventType eventType, + void* data); + + unsigned int windowHandle() const; + void setWindowHandle(unsigned int handle); + + private: + PluginLogic(); + ~PluginLogic(); + + class Impl; + std::unique_ptr m_impl; + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton PluginLogicSingleton; + +#endif // PLUGIN_LOGIC_H diff --git a/src_mobile/plugin-loading/plugin_model.cpp b/src_mobile/plugin-loading/plugin_model.cpp new file mode 100644 index 0000000..ee6dd6f --- /dev/null +++ b/src_mobile/plugin-loading/plugin_model.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_model.cpp + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief This file contains PluginModel, PluginHandle definitions. + */ + +#include "plugin_model.h" +#include +#include + +using namespace WrtDB; + +template +struct BindToPluginDAO : + DPL::Event::BindToDAO +{}; + +template +struct BindToFeatureDAOStatic : + DPL::Event::BindToDAO_Static +{}; + +PluginModel::PluginModel(const WrtDB::DbPluginHandle& handle) : + Handle(this, handle), + LibraryName(this, + BindToPluginDAO::Get), + LibraryPath(this, + BindToPluginDAO::Get), + FeatureHandles(this, + BindToFeatureDAOStatic:: + Get), + LibraryDependencies(this, + BindToPluginDAO::Get), + LibraryInstance(this, PluginPtr()) +{} + +WrtDB::DbPluginHandle PluginModel::getHandle() const +{ + return Handle.Get(); +} diff --git a/src_mobile/plugin-loading/plugin_model.h b/src_mobile/plugin-loading/plugin_model.h new file mode 100644 index 0000000..e834cd1 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_model.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_model.h + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief This file contains PluginModel, PluginHandle definitions. + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_PLUGIN_MODEL_H_ +#define WRT_SRC_PLUGIN_SERVICE_PLUGIN_MODEL_H_ + +#include +#include +#include +#include +#include + +#include +#include +#include + +class PluginModel; + +class PluginModel : public DPL::Event::Model +{ + public: + + /** + * *@brief Plugin handle + */ + DPL::Event::Property Handle; + + /** + * *@brief LibraryName + */ + DPL::Event::Property LibraryName; + + /** + * *@brief Library Path + */ + DPL::Event::Property LibraryPath; + + /** + * *@brief Feature set + */ + DPL::Event::Property + FeatureHandles; + + /** + * *@brief Librarydepencies + */ + DPL::Event::Property + LibraryDependencies; + + /** + * *@brief Library instance Low Level + * */ + DPL::Event::Property LibraryInstance; + + public: + PluginModel(const WrtDB::DbPluginHandle& handle); + + private: + WrtDB::DbPluginHandle getHandle() const; +}; + +typedef DPL::SharedPtr PluginModelPtr; + +#endif diff --git a/src_mobile/plugin-loading/plugin_property_support.cpp b/src_mobile/plugin-loading/plugin_property_support.cpp new file mode 100644 index 0000000..7569de2 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_property_support.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_property_support.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 1.0 + * @brief + */ + +#include "plugin_property_support.h" +#include + +using namespace PluginModule; + +const char *NAVIGATOR_PROPERTY_NAME = "navigator"; +const char *SCALE_PROPERTY_NAME = "scale"; +const char *BUNDLE_PROPERTY_NAME = "__bundle"; +const char *THEME_PROPERTY_NAME = "theme"; + +WindowPropertySupport::WindowPropertySupport( + JSGlobalContextRef context) : + m_scale(0), + m_bundle(""), + m_theme(""), + m_context(context) +{} + +WindowPropertySupport::~WindowPropertySupport() +{} + +float WindowPropertySupport::getScale() const +{ + return m_scale; +} + +std::string WindowPropertySupport::getBundle() const +{ + return m_bundle; +} + +std::string WindowPropertySupport::getTheme() const +{ + return m_theme; +} + +JSGlobalContextRef WindowPropertySupport::getJSContext() const +{ + return m_context; +} + +void WindowPropertySupport::setScaleToNavigatorProperty(const double scale) +{ + _D("set window.navigator.scale: %ld", scale); + m_scale = scale; + setPropertyToNavigator(SCALE_PROPERTY_NAME, + JSValueMakeNumber(m_context, scale)); +} + +void WindowPropertySupport::setBundleToWindowProperty(const char* bundle) +{ + _D("set window.__bundle: %s", bundle); + if (bundle) { + m_bundle = bundle; + JSStringRef bundleString = JSStringCreateWithUTF8CString(bundle); + setPropertyToWindow(BUNDLE_PROPERTY_NAME, + JSValueMakeString(m_context, bundleString)); + JSStringRelease(bundleString); + } +} + +void WindowPropertySupport::setThemeToNavigatorProperty(const char* theme) +{ + _D("set window.navigator.__theme: %s", theme); + if (theme) { + m_theme = theme; + JSStringRef themeString = JSStringCreateWithUTF8CString(theme); + setPropertyToNavigator(THEME_PROPERTY_NAME, + JSValueMakeString(m_context, themeString)); + JSStringRelease(themeString); + } +} + +void WindowPropertySupport::setPropertyToWindow(const char* propertyName, + JSValueRef jsValue) +{ + _D("et property to window : %s", propertyName); + if (propertyName) { + JSObjectRef globalObject = JSContextGetGlobalObject(m_context); + JSStringRef propertyNameString = + JSStringCreateWithUTF8CString(propertyName); + JSObjectSetProperty(m_context, + globalObject, + propertyNameString, + jsValue, + kJSPropertyAttributeReadOnly, + NULL); + JSStringRelease(propertyNameString); + } +} + +void WindowPropertySupport::setPropertyToNavigator(const char* propertyName, + JSValueRef jsValue) +{ + _D("set property to navigator : %s", propertyName); + if (propertyName) { + JSObjectRef globalObject = JSContextGetGlobalObject(m_context); + + JSStringRef navigatorString = + JSStringCreateWithUTF8CString(NAVIGATOR_PROPERTY_NAME); + JSValueRef navigatorValue = JSObjectGetProperty(m_context, + globalObject, + navigatorString, + NULL); + + JSStringRef propertyNameString = + JSStringCreateWithUTF8CString(propertyName); + JSObjectSetProperty(m_context, + JSValueToObject(m_context, navigatorValue, NULL), + propertyNameString, + jsValue, + kJSPropertyAttributeReadOnly, + NULL); + + JSStringRelease(propertyNameString); + JSStringRelease(navigatorString); + } +} + diff --git a/src_mobile/plugin-loading/plugin_property_support.h b/src_mobile/plugin-loading/plugin_property_support.h new file mode 100644 index 0000000..fc946c4 --- /dev/null +++ b/src_mobile/plugin-loading/plugin_property_support.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_property_support.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ +#define _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ + +#include +#include + +namespace PluginModule { +class WindowPropertySupport +{ + public: + float getScale() const; + std::string getBundle() const; + std::string getTheme() const; + JSGlobalContextRef getJSContext() const; + + void setScaleToNavigatorProperty(const double scale); + void setBundleToWindowProperty(const char* bundle); + void setThemeToNavigatorProperty(const char* theme); + + explicit WindowPropertySupport(JSGlobalContextRef m_context); + ~WindowPropertySupport(); + + private: + float m_scale; + std::string m_bundle; // string of base64 encoded bundle + std::string m_theme; + JSGlobalContextRef m_context; + + void setPropertyToWindow(const char* propertyName, JSValueRef jsValue); + void setPropertyToNavigator(const char* propertyName, JSValueRef jsValue); +}; +} // namespace PluginModule + +#endif // _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ diff --git a/src_mobile/plugins-api-support/CMakeLists.txt b/src_mobile/plugins-api-support/CMakeLists.txt new file mode 100644 index 0000000..7a67b5e --- /dev/null +++ b/src_mobile/plugins-api-support/CMakeLists.txt @@ -0,0 +1,70 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Grzegorz Krawczyk (g.krawczyk@samsung.com) +# @version 1.0 +# + +pkg_search_module(dpl REQUIRED dpl-efl) + +set(PLUGINS_API_SUPPORT_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/Plugin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Object.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ObjectFactory.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistration.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistry.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${dpl_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGINS_API_SUPPORT} SHARED + ${PLUGINS_API_SUPPORT_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_API_SUPPORT} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_API_SUPPORT} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_PLUGINS_API_SUPPORT} + ${dpl_LIBRARIES} +) + +INSTALL(TARGETS ${TARGET_PLUGINS_API_SUPPORT} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES + ${CMAKE_CURRENT_SOURCE_DIR}/ExportedApi.h + ${CMAKE_CURRENT_SOURCE_DIR}/Plugin.h + ${CMAKE_CURRENT_SOURCE_DIR}/IObject.h + ${CMAKE_CURRENT_SOURCE_DIR}/ObjectFactory.h + ${CMAKE_CURRENT_SOURCE_DIR}/CallbackSupport.h + ${CMAKE_CURRENT_SOURCE_DIR}/tuple.h + ${CMAKE_CURRENT_SOURCE_DIR}/PluginSignals.h + ${CMAKE_CURRENT_SOURCE_DIR}/SignalSignature.h + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistration.h + DESTINATION include/wrt-plugins-api-support) diff --git a/src_mobile/plugins-api-support/CallbackSupport.h b/src_mobile/plugins-api-support/CallbackSupport.h new file mode 100644 index 0000000..bcaa849 --- /dev/null +++ b/src_mobile/plugins-api-support/CallbackSupport.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file CallbackSupport.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_CALLBACK_SUPPORT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_CALLBACK_SUPPORT_H_ + +#include +#include +#include +#include + +namespace WrtPluginsApi { +template +class CallbackSupport +{ + public: + typedef typename Sig::Signature SlotSignature; + typedef typename Sig::Type SlotType; + typedef std::string GroupType; + typedef std::vector SlotList; + + void Connect(const GroupType& group, const SlotType& slot) + { + auto groupIt = m_slots.find(group); + if (m_slots.end() == groupIt) { + groupIt = m_slots.insert(std::make_pair(group, SlotList())).first; + } + groupIt->second.push_back(slot); + } + + void Disconnect(const GroupType& group) + { + m_slots.erase(group); + } + + template + void Invoke(const Args& ... args) + { + FOREACH(groupIt, m_slots) + { + FOREACH(slotIt, groupIt->second) + { + (*slotIt)(args ...); + } + } + } + + template + void InvokeGroup(const GroupType& group, const Args& ... args) + { + auto groupIt = m_slots.find(group); + + if (m_slots.end() != groupIt) { + FOREACH(slotIt, groupIt->second) + { + (*slotIt)(args ...); + } + } + } + + private: + std::map m_slots; +}; +} +#endif diff --git a/src_mobile/plugins-api-support/ExportedApi.h b/src_mobile/plugins-api-support/ExportedApi.h new file mode 100644 index 0000000..28886d0 --- /dev/null +++ b/src_mobile/plugins-api-support/ExportedApi.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file ExportedApi.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_EXPORTED_API_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_EXPORTED_API_H_ + +#include + +/** + * This file provides definition of entry point to the plugin's shared library + * used by wrt. + * + * Each plugin have to provide 1 symbol which is get by dlsym. + * The name of required symbol is specified by 'GetExportedSymbolName' function + * The type of this symbol is pointer to ExportedApi struct + * + * To allow access to your plugin, you have to: + * + * 1)define 3 functions: + * - Register, + * - Unregister, + * - GetProvidedFeatures + * (names are not important) + * + * 2)define global struct named "dll_api" and initialize it with above functions + * *Example: + * ExportedApi dll_api = {Register, Unregister, GetProvidedFeatures}; + * + * + * Detailed Example how the file with api may looks like file: + * + * #include + * #include + * + * #include + * #include + * #include + * #include + * + * #include "JSTest.h" + * #include "plugin_config.h" + * + * #define OBJECT_WIDGET "widget" + * #define OBJECT_TEST "__test" + * + * using namespace WrtPlugins::W3C; + * using namespace WrtDeviceApis; + * using namespace WrtDeviceApis::Commons; + * using namespace WrtPluginsApi; + * + * namespace W3CTest + * { + * + * void on_widget_start_callback(int widgetId) + * { + * + * } + * + * void on_widget_stop_callback(int widgetId) + * { + * } + * + * } + * + * void Register(PluginRegistration& r) + * { + * Plugin* plugin = new Plugin(); + * + * auto test = ObjectFactory::createMainObject( + * OBJECT_TEST, + * WrtPlugins::W3C::JSTest::getClassRef, + * OBJECT_WIDGET); + * + * plugin->AddObject(test); + * + * r.Connect(W3CTest::on_widget_start_callback); + * + * r.Connect(W3CTest::on_widget_stop_callback); + * + * r.AddPlugin(*plugin); + * } + * + * void Unregister(PluginRegistration& r, Plugin* plugin) + * { + * r.DisconnectAll(); + * delete plugin; + * } + * + * void GetProvidedFeatures(feature_mapping_interface_t *mapping) + * { + * WrtPlugins::W3C::WidgetTestDeclarations::getMappingInterface(mapping); + * } + * + * ExportedApi dll_api={Register, Unregister, GetProvidedFeatures}; + * + * #undef OBJECT_WIDGET + * #undef OBJECT_TEST + * + * + * */ + +//forward declaration +struct feature_mapping_interface_s; +typedef struct feature_mapping_interface_s feature_mapping_interface_t; + +extern "C" struct ExportedApi +{ + /* + * This function is invoked when library is loaded + * */ + void (*Register)(WrtPluginsApi::PluginRegistration&); + + /* + * This function is invoked when library is unloaded + * */ + void (*Unregister)(WrtPluginsApi::PluginRegistration&, + WrtPluginsApi::Plugin* plugin); + + /* + * This function is invoked by wrt-plugins-installer to obtain + * info about features,functions,objects provided by plugin + * */ + void (*GetProvidedFeatures)(feature_mapping_interface_t*); +}; + +constexpr const char* GetExportedSymbolName() +{ + return "dll_api"; +} + +#endif diff --git a/src_mobile/plugins-api-support/IObject.h b/src_mobile/plugins-api-support/IObject.h new file mode 100644 index 0000000..4148d91 --- /dev/null +++ b/src_mobile/plugins-api-support/IObject.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IObject.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_IOBJECT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_IOBJECT_H_ + +#include +#include + +extern "C" { +typedef struct OpaqueJSClass* (*ClassRef)(); +} + +namespace WrtPluginsApi { +enum class IObjectType +{ + Object, + Function, + Interface, + InterfaceInstance +}; + +enum class IObjectOption +{ + Overlayed +}; + +class IObject; +typedef std::shared_ptr IObjectPtr; + +class IObject +{ + public: + constexpr static const char* WINDOW_OBJECT() + { + return "window"; + } + + virtual void AddChild(const IObjectPtr&) = 0; + + /* + * Optional + * */ + virtual void setBoolOption(IObjectOption option, bool value) = 0; + + virtual ~IObject(){} +}; + +typedef std::list IObjectsList; +typedef std::shared_ptr IObjectsListPtr; +} +#endif diff --git a/src_mobile/plugins-api-support/IObject_cast.h b/src_mobile/plugins-api-support/IObject_cast.h new file mode 100644 index 0000000..105a31d --- /dev/null +++ b/src_mobile/plugins-api-support/IObject_cast.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IObject_cast.h + * @author + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGINS_API_SUPPORT_CAST_H_ +#define _WRT_PLUGINS_COMMON_PLUGINS_API_SUPPORT_CAST_H_ + +#include +#include +#include + +namespace WrtPluginsApi { +inline ObjectPtr CAST(const IObjectPtr& object) +{ + return std::dynamic_pointer_cast(object); +} +} +#endif diff --git a/src_mobile/plugins-api-support/Object.cpp b/src_mobile/plugins-api-support/Object.cpp new file mode 100644 index 0000000..7db93e4 --- /dev/null +++ b/src_mobile/plugins-api-support/Object.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Object.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "Object.h" + +namespace WrtPluginsApi { +void Object::AddChild(const IObjectPtr& child) +{ + if (!m_children) { + m_children = IObjectsListPtr(new IObjectsList); + } + m_children->push_back(child); +} + +void Object::setBoolOption(IObjectOption option, bool value) +{ + if (!m_options) { + m_options = ObjectOptionPtr(new ObjectOption); + } + + switch (option) { + case IObjectOption::Overlayed: + m_options->overlayedMode = value; + break; + default: + break; + } +} + +IObjectsListPtr Object::GetChildren() const +{ + return m_children; +} + +ClassRef Object::GetClass() const +{ + return m_classRef; +} + +ClassRef Object::GetClassConstructor() const +{ + return m_constructorRef; +} + +const char* Object::GetInterfaceName() const +{ + return m_interfaceName; +} + +const char* Object::GetName() const +{ + return m_name; +} + +IObjectType Object::GetType() const +{ + return m_type; +} + +const char* Object::GetParentName() const +{ + return m_parentName; +} + +ObjectOptionPtr Object::GetOptions() const +{ + return m_options; +} + +Object::Object(const char* name, + ClassRef ref, + IObjectType type) : + m_name(name), + m_classRef(ref), + m_parentName(0), + m_type(type), + m_interfaceRef(0), + m_interfaceName(0), + m_constructorRef(0) +{} + +Object::Object(const char* name, + ClassRef ref, + const char* parentName, + IObjectType type) : + m_name(name), + m_classRef(ref), + m_parentName(parentName), + m_type(type), + m_interfaceRef(0), + m_interfaceName(0), + m_constructorRef(0) +{} + +Object::Object(const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName, + IObjectType type) : + m_name(name), + m_parentName(parentName), + m_type(type), + m_interfaceRef(interfaceRef), + m_interfaceName(interfaceName), + m_constructorRef(constructorRef) +{} + +Object::~Object() +{} +} diff --git a/src_mobile/plugins-api-support/Object.h b/src_mobile/plugins-api-support/Object.h new file mode 100644 index 0000000..5417453 --- /dev/null +++ b/src_mobile/plugins-api-support/Object.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IObject.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_H_ + +#include +#include + +#include +#include + +namespace WrtPluginsApi { +class Object; +typedef std::shared_ptr ObjectPtr; + +struct ObjectOption +{ + DPL::Optional overlayedMode; +}; +typedef std::shared_ptr ObjectOptionPtr; + +class Object : public IObject +{ + public: + Object(const char* name, + ClassRef ref, + IObjectType type = IObjectType::Object); + + Object(const char* name, + ClassRef ref, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + + Object(const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + + ~Object(); + + void AddChild(const IObjectPtr&); + + void setBoolOption(IObjectOption option, bool value); + + IObjectsListPtr GetChildren() const; + + ClassRef GetClass() const; + + /* + * Available only for object with type InterfaceInstance + * */ + ClassRef GetClassConstructor() const; + + const char* GetInterfaceName() const; + + const char* GetName() const; + + IObjectType GetType() const; + + const char* GetParentName() const; + + ObjectOptionPtr GetOptions() const; + + private: + const char* m_name; + ClassRef m_classRef; + + const char* m_parentName; + + IObjectType m_type; + + ClassRef m_interfaceRef; + const char* m_interfaceName; + ClassRef m_constructorRef; + + ObjectOptionPtr m_options; + + IObjectsListPtr m_children; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/ObjectFactory.cpp b/src_mobile/plugins-api-support/ObjectFactory.cpp new file mode 100644 index 0000000..b897399 --- /dev/null +++ b/src_mobile/plugins-api-support/ObjectFactory.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file ObjectFactory.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "ObjectFactory.h" +#include "Object.h" + +namespace WrtPluginsApi { +namespace ObjectFactory { +IObjectPtr createObject( + const char* name, + ClassRef ref, + IObjectType type) +{ + return IObjectPtr(new Object(name, ref, type)); +} + +IObjectPtr createMainObject( + const char* name, + ClassRef ref, + const char* parentName, + IObjectType type) +{ + return IObjectPtr(new Object(name, ref, parentName, type)); +} + +IObjectPtr createObjectWithInterface( + const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName, + IObjectType type) +{ + return IObjectPtr(new Object(name, + interfaceRef, + interfaceName, + constructorRef, + parentName, + type)); +} +} +} diff --git a/src_mobile/plugins-api-support/ObjectFactory.h b/src_mobile/plugins-api-support/ObjectFactory.h new file mode 100644 index 0000000..59bff1d --- /dev/null +++ b/src_mobile/plugins-api-support/ObjectFactory.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file ObjectFactory.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_FACTORY_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_FACTORY_H_ + +#include +#include + +namespace WrtPluginsApi { +namespace ObjectFactory { +IObjectPtr createObject( + const char* name, + ClassRef ref, + IObjectType type = IObjectType::Object); + +IObjectPtr createMainObject( + const char* name, + ClassRef ref, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + +IObjectPtr createObjectWithInterface( + const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); +} +} +#endif diff --git a/src_mobile/plugins-api-support/Plugin.cpp b/src_mobile/plugins-api-support/Plugin.cpp new file mode 100644 index 0000000..6303c32 --- /dev/null +++ b/src_mobile/plugins-api-support/Plugin.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Plugin.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include "Plugin.h" + +namespace WrtPluginsApi { +void Plugin::AddObject(const IObjectPtr& object) +{ + m_objects->push_back(object); +} + +IObjectsListPtr Plugin::GetObjects() const +{ + return m_objects; +} + +Plugin::~Plugin() +{} + +Plugin::Plugin() : m_objects(new IObjectsList()) +{} +} diff --git a/src_mobile/plugins-api-support/Plugin.h b/src_mobile/plugins-api-support/Plugin.h new file mode 100644 index 0000000..5458714 --- /dev/null +++ b/src_mobile/plugins-api-support/Plugin.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Plugin.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_H_ + +#include +#include + +namespace WrtPluginsApi { +class Plugin +{ + public: + void AddObject(const IObjectPtr& object); + + IObjectsListPtr GetObjects() const; + + Plugin(); + + virtual ~Plugin(); + + private: + IObjectsListPtr m_objects; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/PluginRegistration.cpp b/src_mobile/plugins-api-support/PluginRegistration.cpp new file mode 100644 index 0000000..089fdec --- /dev/null +++ b/src_mobile/plugins-api-support/PluginRegistration.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistration.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "PluginRegistration.h" + +#include "PluginRegistrationImpl.h" +#include "Plugin.h" +#include + +namespace WrtPluginsApi { +PluginRegistration::PluginRegistration(Impl* impl) : m_impl(impl) +{ + Assert(impl != 0 && "impl is NULL"); +} + +template +void PluginRegistration::Connect(const typename SignalSignature::Type& slot) +{ + m_impl->Connect(slot); +} + +void PluginRegistration::DisconnectAll() +{ + m_impl->DisconnectAll(); +} + +void PluginRegistration::AddPlugin(Plugin& plugin) +{ + m_impl->AddPlugin(plugin); +} + +#define EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(SignalSignature) \ + template void PluginRegistration::Connect( \ + const typename SignalSignature::Type &) + +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnWidgetStart); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnWidgetStop); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnFrameLoad); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnFrameUnload); +} diff --git a/src_mobile/plugins-api-support/PluginRegistration.h b/src_mobile/plugins-api-support/PluginRegistration.h new file mode 100644 index 0000000..e871a76 --- /dev/null +++ b/src_mobile/plugins-api-support/PluginRegistration.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistration.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_H_ + +#include +#include "Plugin.h" +#include "PluginSignals.h" + +namespace WrtPluginsApi { +class PluginRegistration +{ + public: + class Impl; + + explicit PluginRegistration(PluginRegistration::Impl* impl); + + template + void Connect(const typename SignalSignature::Type& slot); + + void DisconnectAll(); + + void AddPlugin(Plugin& plugin); + + private: + std::unique_ptr m_impl; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/PluginRegistrationImpl.h b/src_mobile/plugins-api-support/PluginRegistrationImpl.h new file mode 100644 index 0000000..1c17859 --- /dev/null +++ b/src_mobile/plugins-api-support/PluginRegistrationImpl.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistrationImpl.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_IMPL_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_IMPL_H_ + +#include +#include "SignalsSupport.h" +#include "Plugin.h" +#include + +namespace WrtPluginsApi { +class PluginRegistration::Impl +{ + public: + Impl(SignalsSupport& registry, const std::string& libraryName) : + m_registry(registry), + m_libraryName(libraryName) + {} + + void AddPlugin(Plugin& plugin) + { + m_registry.AddPlugin(m_libraryName, plugin); + } + + template + void Connect(const typename T::Type& slot) + { + m_registry.Connect(m_libraryName, slot); + } + + void DisconnectAll() + { + m_registry.Disconnect(m_libraryName); + } + + private: + SignalsSupport& m_registry; + std::string m_libraryName; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/PluginRegistry.cpp b/src_mobile/plugins-api-support/PluginRegistry.cpp new file mode 100644 index 0000000..c4bc496 --- /dev/null +++ b/src_mobile/plugins-api-support/PluginRegistry.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include "PluginRegistry.h" +#include "PluginRegistration.h" +#include "PluginRegistrationImpl.h" +#include "ExportedApi.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace WrtPluginsApi { +void PluginRegistry::AddPlugin(const std::string& libraryName, + Plugin& plugin) +{ + LogDebug("Adding plugin for library: " << libraryName); + + auto libraryIt = m_plugins.find(libraryName); + if (m_plugins.end() == libraryIt) { + m_plugins[libraryName] = &plugin; + } +} + +Plugin* PluginRegistry::GetPlugin(const std::string& libraryName) +{ + auto it = m_plugins.find(libraryName); + if (it == m_plugins.end()) { + if (!LoadFromFile(libraryName)) { + LogError("Failed to load lib" << libraryName); + ThrowMsg(PluginNotFound, "Failed to load plugin"); + } + + return m_plugins[libraryName]; + } + + return it->second; +} + +void PluginRegistry::RemovePlugin(const std::string& libraryName, + Plugin& plugin) +{ + auto it = m_plugins.find(libraryName); + if (it != m_plugins.end()) { + if (&plugin == it->second) { + m_plugins.erase(it); + } + } +} + +void PluginRegistry::UnloadAll() +{ + LogDebug("Unload all plugins"); + + typedef void (*UnregisterFunction)(PluginRegistration&, Plugin&); + + FOREACH(libraryIt, m_libraries) + { + auto pluginIt = m_plugins.find(libraryIt->first); + if (m_plugins.end() != pluginIt) { + void* handle = dlopen(libraryIt->first.c_str(), RTLD_NOW); + if (!handle) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + continue; + } + DPL_SCOPE_EXIT(handle) { + if (dlclose(handle) != 0) { + const char* error = dlerror(); + if (error != NULL) + { + std::string errstr{error}; + _E("%s", errstr.c_str()); + } + else + { + _E("unknown error while closing plug-in library"); + } + } + }; + + ExportedApi* entryPoint = + static_cast + (dlsym(handle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + continue; + } + if (entryPoint->Unregister == NULL) { + LogError("Error Unregister function not set"); + continue; + } + + PluginRegistration registration( + new PluginRegistration::Impl(*this, libraryIt->first)); + + entryPoint->Unregister(registration, (pluginIt->second)); + + m_plugins.erase(pluginIt); + } + dlclose(libraryIt->second); + } +} + +bool PluginRegistry::LoadFromFile(const std::string& libraryName) +{ + void* handle = dlopen(libraryName.c_str(), RTLD_NOW); + if (!handle) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + return false; + } + m_libraries[libraryName] = handle; + + ExportedApi* entryPoint = + static_cast(dlsym(handle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + return false; + } + + if (entryPoint->Register == NULL) { + LogError("Error Register function not set"); + return false; + } + if (entryPoint->Unregister == NULL) { + LogError("Error Unregister function not set"); + return false; + } + + PluginRegistration registration( + new PluginRegistration::Impl(*this, libraryName)); + entryPoint->Register(registration); + + return true; +} + +PluginRegistry::~PluginRegistry() +{ + //TODO discuss ... when the unload should be called + // UnloadAll(); +} +} diff --git a/src_mobile/plugins-api-support/PluginRegistry.h b/src_mobile/plugins-api-support/PluginRegistry.h new file mode 100644 index 0000000..5db1ea4 --- /dev/null +++ b/src_mobile/plugins-api-support/PluginRegistry.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_LOADING_PLUGIN_REGISTRY_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_LOADING_PLUGIN_REGISTRY_H_ + +#include +#include +#include "SignalsSupport.h" +#include "Plugin.h" +#include + +namespace WrtPluginsApi { +typedef std::list PluginsList; +typedef std::shared_ptr PluginsListPtr; +typedef std::map< std::string, PluginsListPtr> PluginsSet; + +class PluginRegistry : public SignalsSupport +{ + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, PluginNotFound) + + template + void Call(Args ... args) + { + Invoke(args ...); + } + + template + void CallGroup(const typename CallbackSupport::GroupType& type, + Args ... args) + { + InvokeGroup(type, args ...); + } + + void AddPlugin(const std::string& libraryName, Plugin& plugin); + + /* + * @throw PluginNotFound + * */ + Plugin* GetPlugin(const std::string& libraryName); + + void RemovePlugin(const std::string& libraryName, Plugin& plugin); + + void UnloadAll(); + + ~PluginRegistry(); + + private: + bool LoadFromFile(const std::string& libraryName); + + typedef void* Symbol; + + std::map m_plugins; + std::map m_libraries; +}; + +typedef std::shared_ptr PluginRegistryPtr; +} + +#endif diff --git a/src_mobile/plugins-api-support/PluginSignals.h b/src_mobile/plugins-api-support/PluginSignals.h new file mode 100644 index 0000000..556d620 --- /dev/null +++ b/src_mobile/plugins-api-support/PluginSignals.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginSignals.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_SIGNALS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_SIGNALS_H_ + +#include "SignalSignature.h" + +namespace WrtPluginsApi { +struct OnWidgetStart : SignalSignature {}; + +struct OnWidgetStop : SignalSignature {}; + +struct OnFrameLoad : SignalSignature {}; + +struct OnFrameUnload : SignalSignature {}; +} + +#endif diff --git a/src_mobile/plugins-api-support/SignalSignature.h b/src_mobile/plugins-api-support/SignalSignature.h new file mode 100644 index 0000000..b43747e --- /dev/null +++ b/src_mobile/plugins-api-support/SignalSignature.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file SignalSignature.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNAL_SIGNATURE_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNAL_SIGNATURE_H_ + +#include + +namespace WrtPluginsApi { +template struct SignalSignature; + +template +struct SignalSignature +{ + typedef R (*Signature)(Args ...); + typedef std::function Type; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/SignalsSupport.h b/src_mobile/plugins-api-support/SignalsSupport.h new file mode 100644 index 0000000..9c47af2 --- /dev/null +++ b/src_mobile/plugins-api-support/SignalsSupport.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IPluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNALS_SUPPORT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNALS_SUPPORT_H_ + +#include +#include +#include "CallbackSupport.h" +#include "tuple.h" +#include "PluginSignals.h" +#include "Plugin.h" + +namespace WrtPluginsApi { +class SignalsSupport +{ + public: + virtual ~SignalsSupport() {} + + template + void Connect(const std::string& libraryName, const typename T::Type& slot) + { + Tuple::get_by_type >(m_slots).Connect(libraryName, + slot); + } + + void Disconnect(const std::string& libraryName) + { + DisconnectGroup(m_slots, libraryName); + } + + virtual void AddPlugin(const std::string& libraryName, Plugin& plugin) = 0; + + protected: + template + void Invoke(const Args& ... args) + { + Tuple::get_by_type >(m_slots).Invoke(args ...); + } + + template + void InvokeGroup(const std::string& libraryName, const Args& ... args) + { + Tuple::get_by_type >(m_slots).InvokeGroup( + libraryName, + args ...); + } + + private: + template + void DisconnectSlot(std::tuple& slots, + const std::string& libraryName, + typename std::enable_if<(N >= 0)>::type* = NULL) + { + std::get(slots).Disconnect(libraryName); + DisconnectSlot(slots, libraryName); + } + + template + void DisconnectSlot(std::tuple& /*slots*/, + const std::string& /*libraryName*/, + typename std::enable_if<(N == -1)>::type* = NULL) + {} + + template + void DisconnectGroup(std::tuple& slots, + const std::string& libraryName) + { + DisconnectSlot(slots, libraryName); + } + + std::tuple, + CallbackSupport, + CallbackSupport, + CallbackSupport > m_slots; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/SoFeatures.h b/src_mobile/plugins-api-support/SoFeatures.h new file mode 100644 index 0000000..a42963e --- /dev/null +++ b/src_mobile/plugins-api-support/SoFeatures.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file + * @author + * @version + * @brief TODO This header must be removed because it does not fit to current + * solution, its just a temporary approach. + */ +#ifndef _WRT_PLUGINS_COMMON_FEATURE_API_SO_FEATURES_H_ +#define _WRT_PLUGINS_COMMON_FEATURE_API_SO_FEATURES_H_ + +#define PLUGIN_WIDGET_INIT_PROC_NAME "on_widget_init" +//#define PLUGIN_WIDGET_INIT_PROC_NAME \ +// "_Z23on_widget_init_callbackP27feature_mapping_interface_s" + +//TODO remove +/* + * list of device caps + */ +typedef struct devcaps_s +{ + char** deviceCaps; + size_t devCapsCount; +} devcaps_t; + +/* + * mapping from a feature to corresponding list of device capabilities + */ +typedef struct feature_devcaps_s +{ + char* feature_name; + devcaps_t devCaps; +} feature_devcaps_t; + +/* + * list of feature_devcaps_t structs + */ +typedef struct feature_mapping_s +{ + feature_devcaps_t* features; + size_t featuresCount; +} feature_mapping_t; + +typedef feature_mapping_t* pfeature_mapping_t; + +typedef pfeature_mapping_t (*features_getter)(void); + +typedef const devcaps_t* (*devcaps_getter)(pfeature_mapping_t /*features*/, + const char* /*featureName*/); +typedef void (*deinitializer)(pfeature_mapping_t /*features*/); + +typedef struct feature_mapping_interface_s +{ + features_getter featGetter; /* returns a list of api features */ + devcaps_getter dcGetter; /* + * for a given api feature returns a list of + * corresponding device capabilities + */ + + deinitializer release; /* as memory ownership of features is + * transfered to callee you have to call + * the release function ptr on features + */ +} feature_mapping_interface_t; + +typedef void (*on_widget_init_proc)(feature_mapping_interface_t *interface); + +#endif diff --git a/src_mobile/plugins-api-support/detail/traits.h b/src_mobile/plugins-api-support/detail/traits.h new file mode 100644 index 0000000..7ab56db --- /dev/null +++ b/src_mobile/plugins-api-support/detail/traits.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file traits.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_DETAIL_TRAITS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_DETAIL_TRAITS_H_ + +namespace WrtPluginsApi { +namespace Traits { +namespace Detail { +template +struct index_of_; + +/* + * CurrentArgType is not equal to RequiredType, check next tuple's argument + */ +template +struct index_of_ +{ + static const size_t value = index_of_::value; +}; + +/* + * RequiredType found on tuple's args list + * return position on tuple's list + */ +template +struct index_of_ +{ + static const size_t value = n; +}; + +/* + * RequiredType found on last position of tuple's args list + * return position on tuple's list + */ +template +struct index_of_ +{ + static const size_t value = n; +}; + +/* + * RequiredType was not found on tuple args list + */ +template +struct index_of_ +{ + static const size_t value = -1; +}; +} +} +} + +#endif diff --git a/src_mobile/plugins-api-support/js_types.h b/src_mobile/plugins-api-support/js_types.h new file mode 100644 index 0000000..387c5bc --- /dev/null +++ b/src_mobile/plugins-api-support/js_types.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_types.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#ifndef WRT_PLUGIN_COMMON_API_SUPPORT_JS_TYPES_H_ +#define WRT_PLUGIN_COMMON_API_SUPPORT_JS_TYPES_H_ + +#include + +//forward declaration +extern "C" { +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +namespace WrtPluginsApi { +struct JavaScriptObject +{ + JSObjectRef instance; + std::string name; +}; +} + +#endif diff --git a/src_mobile/plugins-api-support/traits.h b/src_mobile/plugins-api-support/traits.h new file mode 100644 index 0000000..286c510 --- /dev/null +++ b/src_mobile/plugins-api-support/traits.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file traits.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TRAITS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TRAITS_H_ + +#include "detail/traits.h" + +namespace WrtPluginsApi { +namespace Traits { +/** + * Gets index of specified type in the type list. + */ +template +struct index_of +{ + static const size_t value = Detail::index_of_<0, + RequiredType, + TupleArgTypes ...>::value; +}; +} +} + +#endif diff --git a/src_mobile/plugins-api-support/tuple.h b/src_mobile/plugins-api-support/tuple.h new file mode 100644 index 0000000..ec7c3b3 --- /dev/null +++ b/src_mobile/plugins-api-support/tuple.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file tuple.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TUPLE_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TUPLE_H_ + +#include +#include "traits.h" + +namespace WrtPluginsApi { +namespace Tuple { +template +T& get_by_type(std::tuple& tuple) +{ + return std::get::value>(tuple); +} +} +} + +#endif diff --git a/src_mobile/plugins-installer/CMakeLists.txt b/src_mobile/plugins-installer/CMakeLists.txt new file mode 100644 index 0000000..6c01a00 --- /dev/null +++ b/src_mobile/plugins-installer/CMakeLists.txt @@ -0,0 +1,69 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Andrzej Surdej (a.surdej@samsung.com) +# @version 1.0 +# + +SET(TARGET_PLUGINS_INSTALLER "wrt-plugins-installer") + +SET(WRT_PLUGINS_INSTALLER_SRC_DIR + ${CMAKE_CURRENT_SOURCE_DIR} +) + +PKG_CHECK_MODULES(PLUGINS_INSTALLER_DEPS + libxml-2.0 + cert-svc-vcore + dpl-efl + dpl-wrt-dao-rw + libpcrecpp + REQUIRED +) + +INCLUDE_DIRECTORIES( + ${WRT_PLUGINS_INSTALLER_SRC_DIR} + ${PLUGINS_INSTALLER_INCLUDES} + ${PLUGINS_INSTALLER_DEPS_INCLUDE_DIRS} + ${PLUGINS_API_SUPPORT_DIRS} +) + +SET(WRT_PLUGINS_INSTALLER_SOURCES + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/wrt_plugins_installer.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_installer.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_utils.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_objects.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_metafile_reader.cpp +) + +ADD_DEFINITIONS(${PLUGINS_INSTALLER_DEPS_CFLAGS}) +ADD_DEFINITIONS(${PLUGINS_INSTALLER_DEPS_CFLAGS_OTHERS}) + +ADD_EXECUTABLE(${TARGET_PLUGINS_INSTALLER} + ${WRT_PLUGINS_INSTALLER_SOURCES} +) + +TARGET_LINK_LIBRARIES(${TARGET_PLUGINS_INSTALLER} + ${PLUGINS_INSTALLER_DEPS_LIBRARIES} + ${TARGET_PLUGINS_API_SUPPORT} "-ldl" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_INSTALLER} PROPERTIES + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON +) + +INSTALL(TARGETS ${TARGET_PLUGINS_INSTALLER} DESTINATION bin) diff --git a/src_mobile/plugins-installer/DESCRIPTION b/src_mobile/plugins-installer/DESCRIPTION new file mode 100644 index 0000000..0e8c571 --- /dev/null +++ b/src_mobile/plugins-installer/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Widget (un)installer, plugin (un)installer diff --git a/src_mobile/plugins-installer/plugin_installer.cpp b/src_mobile/plugins-installer/plugin_installer.cpp new file mode 100644 index 0000000..645bc72 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_installer.cpp @@ -0,0 +1,711 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer.cpp + * @author Andrzej Surdej(a.surdej@samgsung.com) + * @version + * @brief + */ + +#include "plugin_installer.h" + +#include +#include +#include +#include + +#include +#include + +#include "plugin_objects.h" +#include "plugin_metafile_reader.h" +#include "plugin_installer_errors.h" + +#include +#include +//#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace WrtDB; +using namespace WrtPluginsApi; + +IMPLEMENT_SINGLETON(PluginsInstaller) + +namespace { +const std::string DIRECTORY_SEPARATOR = std::string("/"); +} + +const int PluginsInstaller::INSTALLATION_ERROR = -1; + +PluginsInstaller::PluginsInstaller() : + m_initialized(false) +{ + LogDebug("PluginsInstaller created."); +} +PluginsInstaller::~PluginsInstaller() +{ + LogDebug("PluginsInstaller destroyed."); +} + +void PluginsInstaller::checkDatabaseTablesExistance() +{ + if (!WrtDB::WrtDatabase::CheckTableExist("FeaturesList") || + !WrtDB::WrtDatabase::CheckTableExist("PluginProperties") || + !WrtDB::WrtDatabase::CheckTableExist("PluginDependencies") || + !WrtDB::WrtDatabase::CheckTableExist("PluginImplementedObjects") || + !WrtDB::WrtDatabase::CheckTableExist("PluginRequiredObjects") || + !WrtDB::WrtDatabase::CheckTableExist("DeviceCapabilities") || + !WrtDB::WrtDatabase::CheckTableExist("FeatureDeviceCapProxy")) + { + LogError("Wrong database. Required tables not exist."); + deinitialize(); + Assert(false && "Wrong database. Required tables not exist."); + } +} + +bool PluginsInstaller::initialize() +{ + LogDebug("Initializing required systems."); + + // Check paths + if (!PluginUtils::checkPaths()) { + return false; + } + // Initialize ValidationCore - this must be done before AttachDatabases + ValidationCore::VCoreInit( + std::string(GlobalConfig::GetFingerprintListFile()), + std::string(GlobalConfig::GetFingerprintListSchema()), + std::string(GlobalConfig::GetVCoreDatabaseFilePath())); + + xmlInitParser(); + WrtDB::WrtDatabase::attachToThreadRW(); + ValidationCore::AttachToThreadRW(); + checkDatabaseTablesExistance(); + LogDebug("Initialized."); + m_initialized = true; + return true; +} + +void PluginsInstaller::deinitialize() +{ + LogDebug("Shuting systems down."); + m_initialized = false; + ValidationCore::DetachFromThread(); + WrtDB::WrtDatabase::detachFromThread(); + ValidationCore::VCoreDeinit(); + xmlCleanupParser(); + LogDebug("Done"); +} + +PluginsInstaller::ReturnStatus PluginsInstaller::installPlugin( + const std::string& libPath) +{ + if (!m_initialized) { + LogError("Plugins installer not initialized."); + return ReturnStatus::NotInitialized; + } + LogDebug("Plugin installation started. Checking path: " << libPath); + + if (!PluginUtils::checkPath(libPath)) { + return ReturnStatus::WrongPluginPath; + } + + LogDebug("Plugin path ok. Searching for config file..."); + + std::string metaFileName = libPath + DIRECTORY_SEPARATOR + + std::string(WrtDB::GlobalConfig::GetPluginMetafileName()); + if (PluginUtils::checkFileExistance(metaFileName)) { + return installPluginFromMetafile(libPath, metaFileName); + } + + PluginMetafileData pluginInfo; + pluginInfo.m_libraryName = getLibraryName(libPath); + + LogDebug( + "Config file done. Lib name: " << pluginInfo.m_libraryName + << + ". Searching for installed plugin..."); + + if (WrtDB::PluginDAO::isPluginInstalled(pluginInfo.m_libraryName)) { + LogDebug("Plugin already installed."); + return ReturnStatus::AlreadyInstalled; + } + LogDebug("Plugin not installed. Loading library file..."); + + PluginObjectsPtr libraryObjects; + PluginHandle pluginHandle; + + std::string filename = libPath + DIRECTORY_SEPARATOR + + pluginInfo.m_libraryName; + + LogDebug("Loading plugin: " << filename); + + Plugin* plugin; + Try + { + plugin = m_registry.GetPlugin(filename); + } + Catch(DPL::Exception) { + LogError("Loading library failed " << filename); + return ReturnStatus::LoadingLibraryError; + } + libraryObjects = PluginObjectsPtr(new PluginObjects()); + + LogDebug("#####"); + LogDebug("##### Plugin: " << filename << " supports new plugin API"); + LogDebug("#####"); + + FOREACH(o, *plugin->GetObjects()) { + libraryObjects->addObjects(CAST(*o)->GetParentName(), + CAST(*o)->GetName()); + + LogDebug("[Parent << Object] " << CAST(*o)->GetParentName() + << " << " + << CAST(*o)->GetName()); + + registerObjects(libraryObjects, plugin->GetObjects()); + } + + if (!fillMappingInterfaces(pluginInfo, filename)) { + m_registry.RemovePlugin(filename, *plugin); + return ReturnStatus::LoadingLibraryError; + } + + LogDebug("Library loaded. Registering plugin..."); + + Try + { + pluginHandle = + PluginDAO::registerPlugin(pluginInfo, libPath); + + LogDebug("Plugin registered. Registering features..."); + + FOREACH(it, pluginInfo.m_featureContainer) + { + LogError("PluginHandle: " << pluginHandle); + FeatureDAO::RegisterFeature(*it, pluginHandle); + } + + LogDebug("Features registered. Registering objects..."); + + registerPluginObjects(pluginHandle, libraryObjects); + + LogDebug("Registration done. Resolving dependencies..."); + + //TODO: can it be replaced with resolvePluginDependencies(handle) + if (!registerAndUpdateInstallation(pluginHandle, libraryObjects)) { + return ReturnStatus::InstallationWaiting; + } + } Catch(DPL::Exception) { + LogError("Failed to make database entry."); + return ReturnStatus::DatabaseError; + } + + LogDebug("Plugin installed successfully."); + return ReturnStatus::Success; +} + +PluginObjectsPtr PluginsInstaller::loadLibraryFromMetafile( + const std::string& libName) const +{ + LogDebug("Loading library: " << libName); + + void *dlHandle = dlopen(libName.c_str(), RTLD_NOW); + if (dlHandle == NULL) { + const char* error = (const char*)dlerror(); + LogError( + "Failed to load plugin: " << libName << + ". Reason: " << (error != NULL ? error : "unknown")); + ThrowMsg(PluginInstall::Exceptions::LibraryException, "Library error"); + } + + const js_entity_definition_t *rawEntityList = NULL; + get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL; + + getWidgetEntityMapProcPtr = + reinterpret_cast(dlsym(dlHandle, + PLUGIN_GET_CLASS_MAP_PROC_NAME)); + + if (getWidgetEntityMapProcPtr) { + rawEntityList = (*getWidgetEntityMapProcPtr)(); + } else { + rawEntityList = + static_cast(dlsym(dlHandle, + PLUGIN_CLASS_MAP_NAME)); + } + + if (rawEntityList == NULL) { + dlclose(dlHandle); + LogError("Failed to read class name" << libName); + ThrowMsg(PluginInstall::Exceptions::LibraryException, "Library error"); + } + + PluginObjectsPtr libraryObjects = PluginObjectsPtr(new PluginObjects()); + const js_entity_definition_t *rawEntityListIterator = rawEntityList; + + LogDebug("#####"); + LogDebug("##### Plugin: " << libName << " is using deprecated API"); + LogDebug("#####"); + + while (rawEntityListIterator->parent_name != NULL && + rawEntityListIterator->object_name != NULL) + { + LogDebug("##### [" << rawEntityListIterator->object_name << "]: "); + LogDebug("##### Parent: " << rawEntityListIterator->parent_name); + LogDebug("#####"); + + libraryObjects->addObjects(rawEntityListIterator->parent_name, + rawEntityListIterator->object_name); + + ++rawEntityListIterator; + } + + // Unload library + if (dlclose(dlHandle) != 0) { + LogError("Cannot close plugin handle"); + } else { + LogDebug("Library is unloaded"); + } + + // Load export table + LogDebug("Library successfuly loaded and parsed"); + + return libraryObjects; +} + +PluginsInstaller::ReturnStatus PluginsInstaller::installPluginFromMetafile( + const std::string& path, const std::string& metaFilePath) +{ + if (!m_initialized) { + LogError("Plugins installer not initialized."); + return ReturnStatus::NotInitialized; + } + OptionalPluginMetafileData pluginData; + Try + { + pluginData = parseMetafile(metaFilePath); + } + Catch(PluginInstall::Exceptions::XMLFileParsingException) + { + LogError("Parsing metafile failed."); + return ReturnStatus::MetafileError; + } + if (pluginData.IsNull()) { + return ReturnStatus::MetafileError; + } + + if (WrtDB::PluginDAO::isPluginInstalled(pluginData->m_libraryName)) { + LogDebug("Plugin already installed."); + return ReturnStatus::AlreadyInstalled; + } + Try { + LogError( + "path is: " << path << ", libraryName: " << + pluginData->m_libraryName); + PluginObjectsPtr objects = loadLibraryFromMetafile( + path + DIRECTORY_SEPARATOR + pluginData->m_libraryName); + + PluginHandle pluginHandle = + PluginDAO::registerPlugin(*pluginData, path); + + LogDebug("Plugin registered. Registering features..."); + + FOREACH(it, pluginData->m_featureContainer) + { + LogError("PluginHandle: " << pluginHandle); + FeatureDAO::RegisterFeature(*it, pluginHandle); + } + + LogDebug("Features registered. Registering objects..."); + + registerPluginObjects(pluginHandle, objects); + + LogDebug("Objects registered. Finishing..."); + + if (!registerAndUpdateInstallation(pluginHandle, objects)) { + return ReturnStatus::InstallationWaiting; + } + } Catch(DPL::Exception) { + LogError("Failed to make database entry."); + return ReturnStatus::DatabaseError; + } + + LogDebug("Plugin installed successfully."); + return ReturnStatus::Success; +} + +int PluginsInstaller::installAllPlugins() +{ + if (!m_initialized) { + LogError("Plugins installer not initialized."); + return INSTALLATION_ERROR; + } + LogDebug("Installing plugins ..."); + + std::string PLUGIN_PATH = std::string(GlobalConfig::GetDevicePluginPath()); + + DIR *dir; + dir = opendir(PLUGIN_PATH.c_str()); + + if (!dir) { + return INSTALLATION_ERROR; + } + + LogDebug("Plugin DIRECTORY IS" << PLUGIN_PATH); + int return_code; + struct dirent libdir; + struct dirent* result; + + errno = 0; + + std::list pluginsPaths; + + for (return_code = readdir_r(dir, &libdir, &result); + result != NULL && return_code == 0; + return_code = readdir_r(dir, &libdir, &result)) { + if (strcmp(libdir.d_name, ".") == 0 || + strcmp(libdir.d_name, "..") == 0) + { + continue; + } + + std::string path = PLUGIN_PATH; + path += "/"; + path += libdir.d_name; + + struct stat tmp; + + if (stat(path.c_str(), &tmp) == -1) { + LogError("Failed to open file" << path); + continue; + } + + if (!S_ISDIR(tmp.st_mode)) { + LogError("Not a directory" << path); + continue; + } + + LogDebug("Found plugin at " << path); + pluginsPaths.push_back(path); + } + + if (0 != return_code) + LogError("Error while reading directory."); + + if (-1 == closedir(dir)) { + LogError("Failed to close dir: " << PLUGIN_PATH); + } + + LogDebug("Plugins to install: " << pluginsPaths.size()); + + for (size_t k = 0; k <= pluginsPaths.size(); ++k) { + printf(" "); + } + printf("]\r["); + int installedPluginsCount = 0; + ReturnStatus ret = ReturnStatus::Unknown; + FOREACH(it, pluginsPaths) { + LogDebug("Preparing to plugin installation: " << *it); + ret = installPlugin(*it); + if (ReturnStatus::Success == ret) { + ++installedPluginsCount; + LogDebug("Plugin " << *it << " installed."); + } else if (ReturnStatus::InstallationWaiting == ret) { + LogWarning("Plugin not installed. Waiting for dependency"); + } else { + LogError("Plugin installation failed"); + } + printf("#"); + fflush(stdout); + } + printf("\n"); + installedPluginsCount += installWaitingPlugins(); + m_registry.UnloadAll(); + LogDebug("Installed " << installedPluginsCount + << " plugins of total: " << pluginsPaths.size()); + return installedPluginsCount; +} + +int PluginsInstaller::installWaitingPlugins() +{ + PluginHandleSetPtr waitingPlugins; + + waitingPlugins = + PluginDAO::getPluginHandleByStatus(PluginDAO::INSTALLATION_WAITING); + + int pluginsInstalled = 0; + FOREACH(it, *waitingPlugins) + { + if (resolvePluginDependencies(*it)) { + ++pluginsInstalled; + } + } + return pluginsInstalled; +} + +bool PluginsInstaller::resolvePluginDependencies(PluginHandle handle) +{ + PluginHandleSetPtr dependencies(new PluginHandleSet); + + PluginObjects::ObjectsPtr requiredObjects = + PluginDAO::getRequiredObjectsForPluginHandle(handle); + + PluginHandle depHandle = INVALID_PLUGIN_HANDLE; + + FOREACH(requiredObject, *requiredObjects) + { + depHandle = + PluginDAO::getPluginHandleForImplementedObject(*requiredObject); + + if (INVALID_PLUGIN_HANDLE == depHandle) { + LogError("Library implementing: " << + *requiredObject << " NOT FOUND"); + return false; + } + dependencies->insert(depHandle); + } + + PluginDAO::registerPluginLibrariesDependencies(handle, dependencies); + PluginDAO::setPluginInstallationStatus(handle, + PluginDAO::INSTALLATION_COMPLETED); + + return true; +} + +void PluginsInstaller::registerObjects(const PluginObjectsPtr& libObj, + const IObjectsListPtr& objects) const +{ + LogDebug("registerObjects invoked"); + + FOREACH(o, *objects) + { + auto children = CAST(*o)->GetChildren(); + + if (children) { + FOREACH(c, *children) + { + libObj->addObjects(CAST(*o)->GetName(), CAST(*c)->GetName()); + + LogDebug("[Parent << Object] " << CAST(*c)->GetName() + << " << " + << CAST(*o)->GetName()); + } + + registerObjects(libObj, children); + } + } +} + +PluginsInstaller::OptionalPluginMetafileData PluginsInstaller::parseMetafile( + const std::string& path) const +{ + LogDebug("Plugin Config file::" << path); + Try + { + PluginMetafileData pluginInfo; + PluginMetafileReader reader; + reader.initialize(path); + reader.read(pluginInfo); + + FOREACH(it, pluginInfo.m_featureContainer) { + LogDebug("Parsed feature : " << it->m_name); + + FOREACH(devCap, it->m_deviceCapabilities) { + LogDebug(" | DevCap : " << *devCap); + } + } + return OptionalPluginMetafileData(pluginInfo); + } + Catch(ValidationCore::ParserSchemaException::Base) { + LogError("Error during file processing " << path); + ThrowMsg(PluginInstall::Exceptions::XMLFileParsingException, + "Parsing metafile failed"); + } +} + +std::string PluginsInstaller::getLibraryName(const std::string& dirPath) const +{ + std::string pluginPath = dirPath; + size_t indexpos = pluginPath.find_last_of('/'); + + if (std::string::npos == indexpos) { + indexpos = 0; + } else { + indexpos += 1; // move after '/' + } + + std::string libName = pluginPath.substr(indexpos); + libName = WrtDB::GlobalConfig::GetPluginPrefix() + libName + + WrtDB::GlobalConfig::GetPluginSuffix(); + LogDebug("Plugin .so: " << libName); + return libName; +} + +bool PluginsInstaller::registerAndUpdateInstallation( + const WrtDB::DbPluginHandle& pluginHandle, + const PluginObjectsPtr& libraries) +{ + PluginHandleSetPtr handles = PluginHandleSetPtr(new PluginHandleSet); + + DbPluginHandle handle = INVALID_PLUGIN_HANDLE; + + //register requiredObjects + FOREACH(it, *(libraries->getDependentObjects())) + { + if (libraries->hasObject(*it)) { + LogDebug("Dependency from the same library. ignored"); + continue; + } + + handle = PluginDAO::getPluginHandleForImplementedObject(*it); + if (handle == INVALID_PLUGIN_HANDLE) { + LogError("Library implementing: " << *it << " NOT FOUND"); + PluginDAO::setPluginInstallationStatus( + pluginHandle, + PluginDAO::INSTALLATION_WAITING); + return false; + } + + handles->insert(handle); + } + + PluginDAO::registerPluginLibrariesDependencies(pluginHandle, handles); + + PluginDAO::setPluginInstallationStatus(pluginHandle, + PluginDAO::INSTALLATION_COMPLETED); + return true; +} + +bool PluginsInstaller::fillMappingInterfaces(PluginMetafileData& pluginData, + const std::string& filename) +{ + void *dlHandle = dlopen(filename.c_str(), RTLD_NOW); + if (dlHandle == NULL) { + const char* error = (const char*)dlerror(); + LogError( + "Failed to load plugin: " << filename << ". Reason: " << (error != NULL ? error : "unknown")); + return false; + } + Try + { + ExportedApi* entryPoint = + static_cast(dlsym(dlHandle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + ThrowMsg(PluginInstall::Exceptions::LibraryException, + "Library error"); + } + + // obtain feature -> dev-cap mapping + feature_mapping_interface_t mappingInterface = { NULL, NULL, NULL }; + entryPoint->GetProvidedFeatures(&mappingInterface); + + if (!mappingInterface.featGetter || !mappingInterface.release || + !mappingInterface.dcGetter) + { + LogError("Failed to obtain mapping interface from .so"); + ThrowMsg(PluginInstall::Exceptions::LibraryException, + "Library error"); + } + + feature_mapping_t* devcapMapping = mappingInterface.featGetter(); + + LogDebug("Getting mapping from features to device capabilities"); + + for (size_t i = 0; i < devcapMapping->featuresCount; ++i) { + PluginMetafileData::Feature feature; + feature.m_name = devcapMapping->features[i].feature_name; + + LogDebug("Feature: " << feature.m_name); + + const devcaps_t* dc = + mappingInterface.dcGetter( + devcapMapping, + devcapMapping->features[i]. + feature_name); + + LogDebug("device=cap: " << dc); + + if (dc) { + LogDebug("devcaps count: " << dc->devCapsCount); + + for (size_t j = 0; j < dc->devCapsCount; ++j) { + LogDebug("devcap: " << dc->deviceCaps[j]); + feature.m_deviceCapabilities.insert(dc->deviceCaps[j]); + } + } + + pluginData.m_featureContainer.insert(feature); + } + + mappingInterface.release(devcapMapping); + } Catch(PluginInstall::Exceptions::PluginsInstallerException) + { + LogError("Exception while feature mapping"); + dlclose(dlHandle); + return false; + } + + // Unload library + if (dlclose(dlHandle) != 0) { + LogError("Cannot close plugin handle"); + } else { + LogDebug("Library is unloaded"); + } + return true; +} + +void PluginsInstaller::registerPluginObjects( + const WrtDB::DbPluginHandle& handle, + const PluginObjectsPtr libObjects) +const +{ + //register implemented objects + PluginObjects::ObjectsPtr objects = + libObjects->getImplementedObject(); + + FOREACH(it, *objects) + { + WrtDB::PluginDAO::registerPluginImplementedObject(*it, handle); + } + + //register requiredObjects + objects = libObjects->getDependentObjects(); + + FOREACH(it, *objects) + { + if (libObjects->hasObject(*it)) { + LogDebug("Dependency from the same library. ignored"); + continue; + } + WrtDB::PluginDAO::registerPluginRequiredObject(*it, handle); + } +} + diff --git a/src_mobile/plugins-installer/plugin_installer.h b/src_mobile/plugins-installer/plugin_installer.h new file mode 100644 index 0000000..2ad33b0 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_installer.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer.h + * @author Andrzej Surdej(a.surdej@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H + +#include +#include +#include +#include +#include + +#include + +class PluginsInstaller +{ + public: + static const int INSTALLATION_ERROR; + enum class ReturnStatus + { + Success, ///< Success + + NotInitialized, ///< Singleton not initialized + WrongPluginPath, ///< ? + MetafileError, ///< ? + AlreadyInstalled, ///< ? + LoadingLibraryError, ///< Loading library by dlopen failed. + /// It may be caused by missing symbols + InstallationWaiting, /// Installation failed due to dependencies + DatabaseError, /// Unable to update database + Unknown ///< Temporary error. Try to not use this. + }; + + bool initialize(); + int installAllPlugins(); + void deinitialize(); + + ReturnStatus installPlugin(const std::string& libPath); + ReturnStatus installPluginFromMetafile(const std::string& libPath, + const std::string& metaFilePath); + + int installWaitingPlugins(); + bool resolvePluginDependencies(PluginHandle handle); + + bool isInitialized(); + + private: + friend class DPL::Singleton; + + PluginsInstaller(); + virtual ~PluginsInstaller(); + + void registerObjects(const PluginObjectsPtr& libObj, + const WrtPluginsApi::IObjectsListPtr& objects) const; + + typedef DPL::Optional OptionalPluginMetafileData; + OptionalPluginMetafileData parseMetafile(const std::string& path) const; + + std::string getLibraryName(const std::string& dirPath) const; + bool registerAndUpdateInstallation(const PluginHandle& pluginHandle, + const PluginObjectsPtr& libraries); + bool fillMappingInterfaces(WrtDB::PluginMetafileData& pluginData, + const std::string& filename); + void registerPluginObjects(const PluginHandle& handle, + const PluginObjectsPtr libObjects) const; + void checkDatabaseTablesExistance(); + PluginObjectsPtr loadLibraryFromMetafile(const std::string& libName) const; + + WrtPluginsApi::PluginRegistry m_registry; + bool m_initialized; + bool m_reinstall; +}; + +typedef DPL::Singleton PluginsInstallerSingleton; + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H */ + diff --git a/src_mobile/plugins-installer/plugin_installer_errors.h b/src_mobile/plugins-installer/plugin_installer_errors.h new file mode 100644 index 0000000..9a94a79 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_installer_errors.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer_errors.h + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H + +#include + +namespace PluginInstall { +namespace Exceptions { +DECLARE_EXCEPTION_TYPE(DPL::Exception, PluginsInstallerException) +DECLARE_EXCEPTION_TYPE(PluginsInstallerException, LibraryException) +DECLARE_EXCEPTION_TYPE(PluginsInstallerException, XMLFileParsingException) +} //namespace +} //namespace + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H */ + diff --git a/src_mobile/plugins-installer/plugin_installer_types.h b/src_mobile/plugins-installer/plugin_installer_types.h new file mode 100644 index 0000000..ae3a5db --- /dev/null +++ b/src_mobile/plugins-installer/plugin_installer_types.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer_types.h + * @author Andrzej Surdej (a.surdej@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H + +#include + +/* Define db type */ +typedef WrtDB::DbWidgetHandle WidgetHandle; +typedef WrtDB::DbWidgetHandleList WidgetHandleList; + +typedef WrtDB::DbWidgetFeature WidgetFeature; +typedef WrtDB::DbWidgetFeatureSet WidgetFeatureSet; + +typedef WrtDB::DbPluginHandle PluginHandle; + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H */ diff --git a/src_mobile/plugins-installer/plugin_metafile_reader.cpp b/src_mobile/plugins-installer/plugin_metafile_reader.cpp new file mode 100644 index 0000000..b65c2e3 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_metafile_reader.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_metafile_reader.cpp + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#include "plugin_metafile_reader.h" + +using namespace WrtDB; + +namespace { +const std::string XML_NAMESPACE = ""; + +const std::string TOKEN_LIBRARY_NAME = "library-name"; +const std::string TOKEN_API_FEATURE = "api-feature"; +const std::string TOKEN_NAME = "name"; +const std::string TOKEN_DEVICECAPABILITY = "device-capability"; +} + +PluginMetafileReader::PluginMetafileReader() : m_parserSchema(this) +{ + m_parserSchema.addEndTagCallback( + TOKEN_LIBRARY_NAME, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndLibraryName); + + m_parserSchema.addEndTagCallback( + TOKEN_API_FEATURE, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndApiFeature); + + m_parserSchema.addEndTagCallback( + TOKEN_NAME, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndName); + + m_parserSchema.addEndTagCallback( + TOKEN_DEVICECAPABILITY, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndDeviceCapability); +} + +void PluginMetafileReader::blankFunction(PluginMetafileData & /* data */) +{} + +void PluginMetafileReader::tokenEndLibraryName(PluginMetafileData &data) +{ + data.m_libraryName = m_parserSchema.getText(); +} + +void PluginMetafileReader::tokenEndApiFeature(PluginMetafileData &data) +{ + data.m_featureContainer.insert(m_feature); + m_feature.m_deviceCapabilities.clear(); +} + +void PluginMetafileReader::tokenEndName(PluginMetafileData & /* data */) +{ + m_feature.m_name = m_parserSchema.getText(); +} + +void PluginMetafileReader::tokenEndDeviceCapability(PluginMetafileData& /*data*/) +{ + m_feature.m_deviceCapabilities.insert(m_parserSchema.getText()); +} + diff --git a/src_mobile/plugins-installer/plugin_metafile_reader.h b/src_mobile/plugins-installer/plugin_metafile_reader.h new file mode 100644 index 0000000..b0c88f0 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_metafile_reader.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_metafile_reader.h + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_METAFILE_READER_H_ +#define WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_METAFILE_READER_H_ + +#include +#include + +class PluginMetafileReader +{ + public: + PluginMetafileReader(); + + void initialize(const std::string &filename) + { + m_parserSchema.initialize(filename, + true, + ValidationCore::SaxReader::VALIDATION_DTD, + std::string()); + } + + void read(WrtDB::PluginMetafileData &data) + { + m_parserSchema.read(data); + } + + private: + void blankFunction(WrtDB::PluginMetafileData &data); + + void tokenEndLibraryName(WrtDB::PluginMetafileData &data); + void tokenEndApiFeature(WrtDB::PluginMetafileData &data); + void tokenEndName(WrtDB::PluginMetafileData &data); + void tokenEndDeviceCapability(WrtDB::PluginMetafileData &data); + + WrtDB::PluginMetafileData::Feature m_feature; + + ValidationCore::ParserSchema m_parserSchema; +}; + +#endif diff --git a/src_mobile/plugins-installer/plugin_objects.cpp b/src_mobile/plugins-installer/plugin_objects.cpp new file mode 100644 index 0000000..ae65b0f --- /dev/null +++ b/src_mobile/plugins-installer/plugin_objects.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_objects.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include +#include +#include "plugin_objects.h" +#include + +namespace { +const char* SEPARATOR = "."; +const std::string GLOBAL_OBJECT_NAME = WrtPluginsApi::IObject::WINDOW_OBJECT(); +const std::string OLD_GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; + +std::string normalizeName(const std::string& objectName) +{ + if (objectName.empty()) { + LogError("Normalize name, name size is 0"); + return objectName; + } + + if (!objectName.compare(0, GLOBAL_OBJECT_NAME.size(), + GLOBAL_OBJECT_NAME)) + { + return objectName; + } + if (!objectName.compare(0, OLD_GLOBAL_OBJECT_NAME.size(), + OLD_GLOBAL_OBJECT_NAME)) + { + return GLOBAL_OBJECT_NAME; + } + + //each object in storage has name started from $GLOBAL_OBJECT_NAME$ + return GLOBAL_OBJECT_NAME + std::string(SEPARATOR) + objectName; +} + +std::string normalizeName(const std::string& objectName, + const std::string& parentName) +{ + if (objectName.empty() || parentName.empty()) { + LogError("Normalize name, name size or parent name size is 0"); + return std::string(); + } + + std::string normalizedName; + normalizedName = normalizeName(parentName) + + std::string(SEPARATOR) + objectName; + + return normalizedName; +} +} + +PluginObjects::PluginObjects() +{ + m_implemented = ObjectsPtr(new Objects()); + m_dependent = ObjectsPtr(new Objects()); +} + +PluginObjects::ObjectsPtr PluginObjects::getImplementedObject() const +{ + return m_implemented; +} + +PluginObjects::ObjectsPtr PluginObjects::getDependentObjects() const +{ + return m_dependent; +} + +void PluginObjects::addObjects(const std::string& parentName, + const std::string& name) +{ + LogDebug("\n Parent: " << parentName + << "\n Name: " << name + << "\n After: Implemented: " << + normalizeName(name, parentName) + << "\n After Dependent: " << + normalizeName(parentName) + ); + + addImplementedObject(normalizeName(name, parentName)); + addDependentObject(normalizeName(parentName)); +} + +void PluginObjects::addDependentObject(const std::string& value) +{ + if (!value.compare(GLOBAL_OBJECT_NAME)) { + //dont add dependency to GLOBAL_OBJECT + return; + } + m_dependent->insert(value); +} + +bool PluginObjects::hasObject(const std::string& name) const +{ + return m_implemented->find(name) != m_implemented->end(); +} + +void PluginObjects::addImplementedObject(const std::string& value) +{ + m_implemented->insert(value); +} diff --git a/src_mobile/plugins-installer/plugin_objects.h b/src_mobile/plugins-installer/plugin_objects.h new file mode 100644 index 0000000..eda28a3 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_objects.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_objects.h + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_OBJECTS_H_ +#define WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_OBJECTS_H_ + +#include +#include +#include +#include + +#include +//TODO TO BE MOVED SOMEWHERE ELSE +// AS OTHER MODULES (LIKE DAO) USE IT + +class PluginObjects : public WrtDB::PluginObjectsDAO +{ + public: + explicit PluginObjects(); + + //getters for objects from library + ObjectsPtr getImplementedObject() const; + ObjectsPtr getDependentObjects() const; + + //add object declaration + void addObjects(const std::string& parentName, + const std::string& name); + + //check if library implemements object given as name + bool hasObject(const std::string& name) const; + + private: + void addImplementedObject(const std::string& value); + void addDependentObject(const std::string& value); +}; + +typedef DPL::SharedPtr PluginObjectsPtr; + +#endif diff --git a/src_mobile/plugins-installer/plugin_utils.cpp b/src_mobile/plugins-installer/plugin_utils.cpp new file mode 100644 index 0000000..42cc49d --- /dev/null +++ b/src_mobile/plugins-installer/plugin_utils.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin-utils.cpp + * @author + * @version 1.0 + * @brief Header file for plugin util + */ + +#include "plugin_utils.h" +#include +#include +#include +#include + +using namespace WrtDB; + +namespace PluginUtils { +//checks if file exists and is regular file +bool checkFileExistance(const std::string& filename) +{ + struct stat tmp; + + if (0 == stat(filename.c_str(), &tmp) && S_ISREG(tmp.st_mode)) { + return true; + } + return false; +} + +std::string cutOffFileName(const std::string& path) +{ + size_t found = path.find_last_of("/"); + if (found == std::string::npos) { + return path; + } else { + return path.substr(0, found); + } +} + +bool checkPath(const std::string& path) +{ + struct stat st; + if (0 == stat(path.c_str(), &st) && S_ISDIR(st.st_mode)) { + return true; + } + LogError("Cannot access directory [ " << path << " ]"); + return false; +} + +bool checkPaths() +{ + bool if_ok = true; + if_ok &= (checkPath(cutOffFileName( + GlobalConfig::GetWrtDatabaseFilePath()))); + if (!if_ok) { + LogError( + "Path <" << GlobalConfig::GetWrtDatabaseFilePath() << + "> does not exist."); + } + + if_ok &= (checkPath(GlobalConfig::GetDevicePluginPath())); + if (!if_ok) { + LogError( + "Path <" << GlobalConfig::GetDevicePluginPath() << + "> does not exist."); + } + + if_ok &= (checkPath(GlobalConfig::GetUserInstalledWidgetPath())); + if (!if_ok) { + LogError( + "Path <" << GlobalConfig::GetUserInstalledWidgetPath() << + "> does not exist."); + } + return if_ok; +} +} //namespace PluginUtils diff --git a/src_mobile/plugins-installer/plugin_utils.h b/src_mobile/plugins-installer/plugin_utils.h new file mode 100644 index 0000000..a542e28 --- /dev/null +++ b/src_mobile/plugins-installer/plugin_utils.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin-utils.h + * @author + * @version 1.0 + * @brief Header file for plugin util + */ +#ifndef PLUGIN_UTILS_H +#define PLUGIN_UTILS_H + +#include +#include + +namespace PluginUtils { +bool checkFileExistance(const std::string& filename); + +std::string cutOffFileName(const std::string& path); +bool checkPath(const std::string& path); +bool checkPaths(); +} +#endif // PLUGIN_UTILS_H diff --git a/src_mobile/plugins-installer/wrt_plugins_installer.cpp b/src_mobile/plugins-installer/wrt_plugins_installer.cpp new file mode 100644 index 0000000..c664350 --- /dev/null +++ b/src_mobile/plugins-installer/wrt_plugins_installer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* @file wrt_plugins_installer.cpp + * @author Andrzej Surdej(a.surdej@gmail.com) + * @version 1.0 + * @brief Main file for plugins installer + */ + +#include +#include +#include +#include +#include + +int main(int /*argc*/, char */*argv*/[]) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + DPL::Log::LogSystemSingleton::Instance().SetTag("PLUGINS_INSTALLER"); + LogDebug("Plugins installation started."); + + printf("Installing plugins...\n"); + PluginsInstallerSingleton::Instance().initialize(); + int installed = + PluginsInstallerSingleton::Instance().installAllPlugins(); + PluginsInstallerSingleton::Instance().deinitialize(); + printf("Completed: %d plugins installed.\n", installed); + + LogDebug("All plugins installed successfuly"); + return 0; + } + UNHANDLED_EXCEPTION_HANDLER_END +} diff --git a/src_mobile/plugins-ipc-message/CMakeLists.txt b/src_mobile/plugins-ipc-message/CMakeLists.txt new file mode 100644 index 0000000..d3da03e --- /dev/null +++ b/src_mobile/plugins-ipc-message/CMakeLists.txt @@ -0,0 +1,60 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Jihoon Chung (jihoon.chung@samsung.com) +# @version 1.0 +# + +pkg_search_module(dpl REQUIRED dpl-efl) +pkg_search_module(webkit2 REQUIRED ewebkit2) + +set(PLUGINS_IPC_MESSAGE_SOURCES + ${PLUGINS_IPC_MESSAGE_DIRS}/ipc_message_support.cpp +) + +INCLUDE_DIRECTORIES( + ${PLUGINS_IPC_MESSAGE_DIRS} + ${webkit2_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGINS_IPC_MESSAGE_LIB} SHARED + ${PLUGINS_IPC_MESSAGE_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_PLUGINS_IPC_MESSAGE_LIB} + ${dpl_LIBRARIES} + ${webkit2_LIBRARIES} +) + +INSTALL(TARGETS ${TARGET_PLUGINS_IPC_MESSAGE_LIB} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES + ipc_message_support.h + DESTINATION include/plugins-ipc-message) diff --git a/src_mobile/plugins-ipc-message/ipc_message_support.cpp b/src_mobile/plugins-ipc-message/ipc_message_support.cpp new file mode 100644 index 0000000..d848d26 --- /dev/null +++ b/src_mobile/plugins-ipc-message/ipc_message_support.cpp @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file ipc_message_support.cpp + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation of IPC between plugins and UI Process + */ +#include "ipc_message_support.h" + +#include +#include +#include +#include +#include +#include +#include + +static WKBundleRef s_injectedBundleRef = NULL; +static unsigned int s_xWindowHandle = 0; + +namespace { +const char* const TIZEN_GET_WINDOW_HANDLE = "tizen://getWindowHandle"; +const char* const TIZEN_CLEAR_ALL_COOKIES = "tizen://clearAllCookies"; + +static std::string toString(WKStringRef str) +{ + if (WKStringIsEmpty(str)) { + return std::string(); + } + size_t size = WKStringGetMaximumUTF8CStringSize(str); + char buffer[size + 1]; + WKStringGetUTF8CString(str, buffer, size + 1); + return buffer; +} + +static std::string sendSyncMessage(const char* name, const char* body) +{ + WKStringRef nameWKString = WKStringCreateWithUTF8CString(name); + WKStringRef bodyWKString = NULL; + if (body) { + bodyWKString = WKStringCreateWithUTF8CString(body); + } + WKTypeRef retWKType = NULL; + WKBundlePostSynchronousMessage(s_injectedBundleRef, + nameWKString, + bodyWKString, + &retWKType); + WKRelease(nameWKString); + if (bodyWKString) { + WKRelease(bodyWKString); + } + if (retWKType) { + std::string retString = toString(static_cast(retWKType)); + WKRelease(retWKType); + return retString; + } else { + return std::string(); + } +} + +static void sendPostMessage(const char* name, const char* body) +{ + WKStringRef nameWKString = WKStringCreateWithUTF8CString(name); + WKStringRef bodyWKString = NULL; + if (body) { + bodyWKString = WKStringCreateWithUTF8CString(body); + } + WKTypeRef retWKType = NULL; + WKBundlePostMessage(s_injectedBundleRef, + nameWKString, + bodyWKString); + WKRelease(nameWKString); + if (bodyWKString) { + WKRelease(bodyWKString); + } +} + +static int sendAsyncMessage(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data) +{ + using namespace IPCMessageSupport; + + int handle = AsyncConnectionManager::instance().addConnection(AsyncConnectionPtr(new AsyncConnection(replyCallback, data))); + + std::string strBody = body; + std::stringstream ss; + + ss << handle; + strBody = ss.str() + "_" + strBody; + + sendPostMessage(name, strBody.c_str()); + + return handle; +} + +} // namespace + + +namespace IPCMessageSupport { + +AsyncConnectionManager::~AsyncConnectionManager() +{ + m_connectionMap.clear(); +} + +AsyncConnectionManager &AsyncConnectionManager::instance() +{ + static AsyncConnectionManager instance; + + return instance; +} + +int AsyncConnectionManager::addConnection(AsyncConnectionPtr connection) +{ + static int latestHandle = -1; + int newHandle; + + latestHandle++; + if (latestHandle < 0) latestHandle = 0; + + newHandle = latestHandle; + + m_connectionMap.insert(AsyncConnectionMap::value_type(newHandle, connection)); + + return newHandle; +} + +bool AsyncConnectionManager::removeConnection(int handle) +{ + bool ret = (m_connectionMap.erase(handle) == 1); + + return ret; +} + +AsyncConnectionPtr AsyncConnectionManager::getConnection(int handle) +{ + AsyncConnectionMap::iterator iter = m_connectionMap.find(handle); + + if (iter != m_connectionMap.end()) + { + return iter->second; + } + + return AsyncConnectionPtr(); +} + + +} // namespace IPCMessageSupport + + +void IPCMessageSupport::setWKBundleRef(WKBundleRef bundleRef) +{ + _D("called"); + s_injectedBundleRef = bundleRef; +} + +void IPCMessageSupport::setXwindowHandle(unsigned int handle) +{ + _D("called"); + s_xWindowHandle = handle; +} + +const char* IPCMessageSupport::sendMessageToUiProcess( + const char* name, + const char* body) +{ + _D("called"); + if (s_injectedBundleRef == NULL) { + _E("UI Process information isn't set"); + return NULL; + } + _D("name = [%s]", name); + if (body) { + _D("body = [%s]", body); + } + + if (!name) { + return NULL; + } + + // tizen://getWindowHandle + if (!strcmp(name, TIZEN_GET_WINDOW_HANDLE)) { + if (s_xWindowHandle == 0) { + return NULL; + } else { + std::stringstream ss; + ss << s_xWindowHandle; + std::string ret = ss.str(); + return strdup(ret.c_str()); + } + } + + // tizen://clearAllCookies + if (!strcmp(name, TIZEN_CLEAR_ALL_COOKIES)) { + sendPostMessage(name, body); + return NULL; + } + + return NULL; +} + +int IPCMessageSupport::sendAsyncMessageToUiProcess(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data) +{ + _D("called"); + + if (s_injectedBundleRef == NULL) + { + _E("UI Process information isn't set"); + return -1; + } + + if (name == NULL) + { + _E("msg name is null!"); + return -1; + } + + if (body == NULL) + { + body = ""; + } + + _D("name = [%s]", name); + if (!body) { + _D("body = [%s]", body); + } + + return sendAsyncMessage(name, body, replyCallback, data); +} + +void* IPCMessageSupport::ignoreAsyncMessageReply(int handle) +{ + _D("called"); + + AsyncConnectionPtr connection = AsyncConnectionManager::instance().getConnection(handle); + + if (!connection) + { + return NULL; + } + + AsyncConnectionManager::instance().removeConnection(handle); + + return connection->data; +} + +void IPCMessageSupport::replyAsyncMessageToWebProcess(Ewk_Context* ewkContext, int handle, const char* body) +{ + _D("called"); + + if (ewkContext == NULL) + { + return; + } + + std::string strBody = (body) ? (body) : ""; + std::stringstream ss; + ss << handle; + + strBody = ss.str() + "_" + strBody; + + ewk_context_message_post_to_injected_bundle(ewkContext, REPLY_ASYNC, strBody.c_str()); +} diff --git a/src_mobile/plugins-ipc-message/ipc_message_support.h b/src_mobile/plugins-ipc-message/ipc_message_support.h new file mode 100644 index 0000000..b5463e9 --- /dev/null +++ b/src_mobile/plugins-ipc-message/ipc_message_support.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. + */ +/** + * @file ipc_message_support.h + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation of IPC between plugins and UI Process + */ +#ifndef WRT_SRC_IPC_MESSAGE_SUPPORT +#define WRT_SRC_IPC_MESSAGE_SUPPORT + +#include +#include +#include +#include +#include + +typedef void (*AsyncReplyCallback)(unsigned int, void*, const char*); + +namespace IPCMessageSupport { + +static const char * const REPLY_ASYNC = "ToInjectedBundle::REPLY_ASYNC"; +static const char * const TIZEN_CHANGE_USERAGENT = "tizen://changeUA"; +static const char * const TIZEN_DELETE_ALL_COOKIES = "tizen://deleteAllCookies"; +static const char * const TIZEN_EXIT = "tizen://exit"; +static const char * const TIZEN_HIDE = "tizen://hide"; + +class AsyncConnection +{ + public: + AsyncReplyCallback replyCallback; + void* data; + + AsyncConnection(AsyncReplyCallback r, void* d) : + replyCallback(r), + data(d) + { + } +}; + +typedef std::shared_ptr AsyncConnectionPtr; +typedef std::map AsyncConnectionMap; + +class AsyncConnectionManager +{ + private: + AsyncConnectionMap m_connectionMap; + + public: + ~AsyncConnectionManager(); + + // Singleton + static AsyncConnectionManager &instance(); + + int addConnection(AsyncConnectionPtr connection); + bool removeConnection(int handle); + AsyncConnectionPtr getConnection(int handle); + +}; + +void setWKBundleRef(WKBundleRef bundleRef); +void setXwindowHandle(unsigned int handle); +const char* sendMessageToUiProcess(const char* name, const char* body); +int sendAsyncMessageToUiProcess(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data); +void* ignoreAsyncMessageReply(int handle); +void replyAsyncMessageToWebProcess(Ewk_Context* ewkContext, int handle, const char* body); +} + +#endif // WRT_SRC_IPC_MESSAGE_SUPPORT diff --git a/src_mobile/standards/CMakeLists.txt b/src_mobile/standards/CMakeLists.txt new file mode 100644 index 0000000..83ff664 --- /dev/null +++ b/src_mobile/standards/CMakeLists.txt @@ -0,0 +1,16 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +add_subdirectory(W3C) diff --git a/src_mobile/standards/W3C/CMakeLists.txt b/src_mobile/standards/W3C/CMakeLists.txt new file mode 100644 index 0000000..11828fb --- /dev/null +++ b/src_mobile/standards/W3C/CMakeLists.txt @@ -0,0 +1,15 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +add_subdir(Widget) diff --git a/src_mobile/standards/W3C/DESCRIPTION b/src_mobile/standards/W3C/DESCRIPTION new file mode 100644 index 0000000..8e32c7b --- /dev/null +++ b/src_mobile/standards/W3C/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +W3C plugin - Widget Interface diff --git a/src_mobile/standards/W3C/Widget/CMakeLists.txt b/src_mobile/standards/W3C/Widget/CMakeLists.txt new file mode 100644 index 0000000..a76454d --- /dev/null +++ b/src_mobile/standards/W3C/Widget/CMakeLists.txt @@ -0,0 +1,49 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +ADD_DEFINITIONS("-DWRT_PLUGINS_WIDGET_LOG") + +set(TARGET_NAME "wrt-plugins-w3c-widget-interface") + +pkg_search_module(webkit2 REQUIRED ewebkit2) +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) + +set(SRCS + ${SRCS_COMMONS} + JSWidget.cpp + JSPreferences.cpp + plugin_initializer.cpp + plugin_config.cpp +) + +include_directories( + ${API_WIDGET_PATH} + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} + ${TARGET_JS_OVERLAY} + wrt-plugins-widget + wrt-plugins-localstorage + wrt-plugins-storageevent + wrt-dispatch-event +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION /usr/lib/wrt-plugins/w3c-widget-interface) diff --git a/src_mobile/standards/W3C/Widget/JSPreferences.cpp b/src_mobile/standards/W3C/Widget/JSPreferences.cpp new file mode 100644 index 0000000..1b3785b --- /dev/null +++ b/src_mobile/standards/W3C/Widget/JSPreferences.cpp @@ -0,0 +1,528 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSPreferences.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#include "JSPreferences.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// import temporarily from JSContextRefPrivate.h +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +using namespace std; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::LocalStorage::Api; +using namespace WrtDeviceApis::StorageEvent::Api; + +#define PREFERENCES_PLUGIN_NAME "preferences" +#define LOCAL_STORAGE_PROPERTY_LENGTH "length" + +#define CATCH_EXCEPTION_NO_MODIFABLE \ + Catch(Commons::LocalStorageValueNoModifableException) { \ + _E("The item is read only"); \ + return JSDOMExceptionFactory:: \ + NoModificationAllowedException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + _E("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + _E("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + _E("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + _E("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_OUT_OF_RANGE \ + Catch(Commons::OutOfRangeException) { \ + _E("OutOfRangeException"); \ + return JSDOMExceptionFactory:: \ + QuotaExceededException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_INVALID_ARG \ + Catch(Commons::InvalidArgumentException) { \ + _E("Pair for given key doesnt exist"); \ + return JSValueMakeNull(context); \ + } + +namespace WrtPlugins { +namespace W3C { +ILocalStoragePtr getIStorage(JSObjectRef arg) +{ + _D("get localstorage object"); + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + _E("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->istorage; +} + +JSObjectRef getWidgetObject(JSObjectRef arg) +{ + _D("get widget object"); + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + _E("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->widgetObject; +} + +enum class ModificationType +{ + RemoveItem, + SetItem +}; + +//this function may throw exceptions +IStorageEventPtr modifyItemAndCreateEvent(ModificationType type, + JSObjectRef thisObject, + const string& key, + const string& value = std::string()) +{ + DPL::Optional oldValue = + getIStorage(thisObject)->getValue(key); + + if (ModificationType::SetItem == type) { + getIStorage(thisObject)->setItem(key, value, false); + } else if (ModificationType::RemoveItem == type) { + getIStorage(thisObject)->removeItem(key); + } else { + Assert(0 && "Wrong Modification type"); + } + + DPL::Optional newValue = + getIStorage(thisObject)->getValue(key); + + //create event object + IStorageEventPtr storageEvent = getStorageEvent(); + + //key + storageEvent->setKey(key); + //oldvalue + if (!!oldValue) { + storageEvent->setOldValue(*oldValue); + } + //newValue + if (!!newValue) { + storageEvent->setNewValue(*newValue); + } + + return storageEvent; +} + +JSClassDefinition JSPreferences::m_classInfo = { + 0, + kJSClassAttributeNone, + PREFERENCES_PLUGIN_NAME, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticFunction JSPreferences::m_function[] = { + { "setItem", JSPreferences::setItem, kJSPropertyAttributeNone }, + { "removeItem", JSPreferences::removeItem, kJSPropertyAttributeNone }, + { "getItem", JSPreferences::getItem, kJSPropertyAttributeNone }, + { "clear", JSPreferences::clear, kJSPropertyAttributeNone }, + { "key", JSPreferences::key, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSPreferences::m_property[] = { + { LOCAL_STORAGE_PROPERTY_LENGTH, + JSPreferences::getLength, + NULL, + kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSPreferences::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSPreferences::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSPreferences::m_jsClassRef = + JSClassCreate(JSPreferences::getClassInfo()); + +void JSPreferences::initialize(JSContextRef context, + JSObjectRef object) +{ + _D("entered. Context: %p", context); + + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(object)); + + Assert(priv && "private object of preferences is NULL"); +} + +void JSPreferences::finalize(JSObjectRef object) +{ + _D("entered"); + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(object)); + + delete priv; +} + +JSValueRef JSPreferences::removeItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + Converter converter(context); + + std::string key = converter.toString(arguments[0]); + + DPL::Optional oldValue = getIStorage(thisObject)->getValue(key); + getIStorage(thisObject)->removeItem(key); + DPL::Optional newValue = getIStorage(thisObject)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValue, newValue, ""); + + return JSValueMakeNull(context); + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::setItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + Converter converter(context); + + std::string key = converter.toString(arguments[0]); + std::string value = converter.tryString(arguments[1]); + + DPL::Optional oldValue = getIStorage(thisObject)->getValue(key); + getIStorage(thisObject)->setItem(key, value, false); + DPL::Optional newValue = getIStorage(thisObject)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValue, newValue, ""); + + return JSValueMakeUndefined(context); + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_OUT_OF_RANGE +} + +JSValueRef JSPreferences::clear(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef /*arguments*/[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + getIStorage(thisObject)->clear(false); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + const auto& null = DPL::Optional::Null; + + DispatchEventSupport::dispatchStorageEvent(g_context, null, null, null, ""); + + return JSValueMakeNull(context); + } + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::getItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + Converter converter(context); + + std::string key = converter.tryString(arguments[0]); + + _D("Getting item for key %s", key.c_str()); + + DPL::Optional value = + getIStorage(thisObject)->getValue(key); + + if (!value) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(*value); + } + } + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::key(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + if (argumentCount < 1) { + _E("No argument found"); + Throw(Commons::InvalidArgumentException); + } + + Converter converter(context); + + size_t n = converter.toSizeT(arguments[0]); + + std::string value = getIStorage(thisObject)->getKeyByIndex(n); + + return converter.toJSValueRef(value); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_INVALID_ARG +} + +JSValueRef JSPreferences::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + _D("enter"); + + Try + { + Converter converter(context); + + size_t value = getIStorage(object)->getStorageSize(); + return converter.toJSValueRef(value); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSPreferences::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + _D("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + if (!getIStorage(object)->getValue(key)) { + return false; + } else { + return true; + } + } + + Catch(Commons::InvalidArgumentException) { + _E("Pair for given key doesnt exist"); + } + + Catch(Commons::ConversionException) { + _E("Error on conversion"); + } + + Catch(Commons::NullPointerException) { + _E("Error on pointer, null value"); + } + + Catch(Commons::PlatformException){ + _E("PlatformException occured"); + } + return false; +} + +JSValueRef JSPreferences::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + _D("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + DPL::Optional value = + getIStorage(object)->getValue(key); + + if (!value) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(*value); + } + } + + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSPreferences::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef jvalue, + JSValueRef* exception) +{ + _D("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + std::string value = converter.toString(jvalue); + + DPL::Optional oldValue = getIStorage(object)->getValue(key); + getIStorage(object)->setItem(key, value, false); + DPL::Optional newValue = getIStorage(object)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + std::string oldValueStr = ""; + std::string newValueStr = ""; + + if (!!oldValue) { oldValueStr = *oldValue; } + if (!!newValue) { newValueStr = *newValue; } + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValueStr, newValueStr, ""); + + return true; + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_OUT_OF_RANGE + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + + return false; +} + +#undef CATCH_EXCEPTION_NO_MODIFABLE +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +#undef CATCH_EXCEPTION_OUT_OF_RANGE +#undef CATCH_EXCEPTION_INVALID_ARG +} +} diff --git a/src_mobile/standards/W3C/Widget/JSPreferences.h b/src_mobile/standards/W3C/Widget/JSPreferences.h new file mode 100644 index 0000000..b86bae8 --- /dev/null +++ b/src_mobile/standards/W3C/Widget/JSPreferences.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSPreferences.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_WIDGET_PREFERENCES_H_ +#define _WRT_PLUGIN_JS_WIDGET_PREFERENCES_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +struct LocalStoragePrivateData { + WrtDeviceApis::LocalStorage::Api::ILocalStoragePtr istorage; + //parent + JSObjectRef widgetObject; +}; + +class JSPreferences +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks + * that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function. + */ + static JSStaticFunction m_function[]; + + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + //Modified functions for Preference object + static JSValueRef removeItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef clear(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef key(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; +} +} + +#endif diff --git a/src_mobile/standards/W3C/Widget/JSWidget.cpp b/src_mobile/standards/W3C/Widget/JSWidget.cpp new file mode 100644 index 0000000..f4b9684 --- /dev/null +++ b/src_mobile/standards/W3C/Widget/JSWidget.cpp @@ -0,0 +1,560 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSWidget.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#include "JSWidget.h" +#include +#include +#include +#include +#include +#include +#include "JSPreferences.h" +#include +#include +#include + +// temporary +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +#define CATCH_EXCEPTION_NO_MODIFABLE \ + Catch(Commons::LocalStorageValueNoModifableException) { \ + LogError("The item is read only"); \ + return JSDOMExceptionFactory:: \ + NoModificationAllowedException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + LogError("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_OUT_OF_RANGE \ + Catch(Commons::OutOfRangeException) { \ + LogError("OutOfRangeException"); \ + return JSDOMExceptionFactory:: \ + QuotaExceededException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_INVALID_ARG \ + Catch(Commons::InvalidArgumentException) { \ + LogError("Pair for given key doesnt exist"); \ + return JSValueMakeNull(context); \ + } + +#define WIDGET_PLUGIN_NAME "Widget" + +#define WRT_WIDGET_PROPERTY_AUTHOR "author" +#define WRT_WIDGET_PROPERTY_AUTHOR_EMAIL "authorEmail" +#define WRT_WIDGET_PROPERTY_AUTHOR_HREF "authorHref" +#define WRT_WIDGET_PROPERTY_DESCRIPTION "description" +#define WRT_WIDGET_PROPERTY_ID "id" +#define WRT_WIDGET_PROPERTY_NAME "name" +#define WRT_WIDGET_PROPERTY_SHORT_NAME "shortName" +#define WRT_WIDGET_PROPERTY_VERSION "version" +#define WRT_WIDGET_PROPERTY_HEIGHT "height" +#define WRT_WIDGET_PROPERTY_WIDTH "width" + +namespace WrtPlugins { +namespace W3C { +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Widget; + +struct WidgetPrivateObject +{ + Widget::Api::IWidgetPtr iwidget; + JSObjectRef preferencesObject; + //TEMP + //int widgetId // TODO: check is it necessary (g.rynkowski) + JSObjectRef widgetObject; +}; +typedef std::shared_ptr WidgetPrivateObjectPtr; + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT +::Type JSWidgetPrivateObject; + +WrtDeviceApis::Widget::Api::IWidgetPtr getIWidget(JSObjectRef arg) +{ + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject()->iwidget; +} + +LocalStorage::Api::ILocalStoragePtr getLocalStorage(int widgetId) +{ + LocalStorage::Api::ILocalStoragePtr storage( + LocalStorage::Api::getLocalStorage(widgetId)); + + return storage; +} + +JSObjectRef getPreferences(JSObjectRef arg) +{ + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + return NULL; + } + + return priv->getObject()->preferencesObject; +} + +JSObjectRef createPreferencesObject(JSContextRef context, + JSObjectRef widgetObject, + int widgetId) +{ + Assert(widgetObject && "Widget Object can'n be null"); + //delete is invoked in JSPreferences::finalize + LocalStoragePrivateData* priv = new LocalStoragePrivateData; + Assert(priv && "Private data is null"); + priv->istorage = getLocalStorage(widgetId); + priv->widgetObject = widgetObject; + + JSObjectRef preferences = JSObjectMake(context, + JSPreferences::getClassRef(), + priv); + + if (!preferences) { + LogError("Preferences object is null"); + delete priv; + } + //Unprotect is called in JSWidget::finalize + JSValueProtect(context, preferences); + + return preferences; +} + +JSClassDefinition JSWidget::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + callAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSWidget::m_property[] = { + { WRT_WIDGET_PROPERTY_AUTHOR, JSWidget::getAuthor, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_AUTHOR_EMAIL, JSWidget::getAuthorEmail, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_AUTHOR_HREF, JSWidget::getAuthorHref, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_DESCRIPTION, JSWidget::getDescription, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_ID, JSWidget::getId, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_NAME, JSWidget::getName, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_SHORT_NAME, JSWidget::getShortName, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_VERSION, JSWidget::getVersion, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_HEIGHT, JSWidget::getHeight, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_WIDTH, JSWidget::getWidth, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSWidget::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSWidget::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSWidget::m_jsClassRef = JSClassCreate(JSWidget::getClassInfo()); + +void JSWidget::initialize(JSContextRef context, + JSObjectRef object) +{ + JSGlobalContextRef g_context = JSContextGetGlobalContext(context); + + LogDebug("entered. Context : " << context << "(global:" << g_context << "), Object: " << object); + + if (context != g_context) + { + context = g_context; + } + + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + if (!priv) { + LogDebug("creation private object"); + + Try { + using namespace WrtDeviceApis::Commons; + + Widget::Api::IWidgetPtr widget = + Api::WidgetFactory::createWidget(); + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + JSObjectRef preferences = + createPreferencesObject(context, + object, + widgetId); + if (!preferences) { + LogError("Failed to create preferences object"); + } + + WidgetPrivateObjectPtr widgetPriv(new WidgetPrivateObject); + widgetPriv->iwidget = widget; + widgetPriv->preferencesObject = preferences; + + priv = new JSWidgetPrivateObject(context, widgetPriv); + JSObjectSetPrivate(object, priv); + } + Catch(Commons::InvalidArgumentException){ + LogError("You should register widget id in ON_WIDGET_START"); + return; + } + Catch(DPL::Exception) { + LogError("Failed to create private object for JSWidget"); + return; + } + } +} + +void JSWidget::finalize(JSObjectRef object) +{ + LogDebug("entered"); + LogDebug("Object: " << object); + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + if (priv) { + JSValueUnprotect(priv->getContext(), + priv->getObject()->preferencesObject); + + delete priv; + LogDebug("private object is released"); + } else { + LogDebug("private object wasn't created"); + } +} + +JSValueRef JSWidget::getAuthor(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthor()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getAuthorEmail(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthorEmail()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getAuthorHref(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthorHref()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getDescription(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getDescription()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getId(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getId()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getName(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getName()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getShortName(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getShortName()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getVersion()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getHeight(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + unsigned int height = getIWidget(object)->getHeight(); + if (0 == height) { + height = 1; + } + return converter.toJSValueRef(height); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getWidth(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + unsigned int width = getIWidget(object)->getWidth(); + if (0 == width) { + width = 1; + } + return converter.toJSValueRef(width); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +bool JSWidget::hasProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName) +{ + LogDebug("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + if (key == "preferences") { + return true; + } + } + Catch(Commons::InvalidArgumentException) { + LogDebug("Pair for given key doesnt exist"); + } + + Catch(Commons::ConversionException) { + LogError("Error on conversion"); + } + + Catch(Commons::NullPointerException) { + LogError("Error on pointer, null value"); + } + + Catch(Commons::PlatformException){ + LogError("PlatformException occured"); + } + return false; +} + +JSValueRef JSWidget::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Object: " << object); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + if (key == "preferences") { + Converter converter(context); + JSObjectRef pref = getPreferences(object); + if (!pref) { + LogError("Preferences object is NULL"); + return JSValueMakeUndefined(context); + } + return pref; + } + LogError("Property NOT supported: " << propertyName); + return JSValueMakeUndefined(context); + } + + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSWidget::setProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName, + JSValueRef /*jvalue*/, + JSValueRef* exception) +{ + LogDebug("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + if (key == "preferences") { + LogError("Object is read only"); + return true; + } + } + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + + return false; +} + +JSObjectRef JSWidget::callAsConstructor(JSContextRef context, + JSObjectRef /*constructor*/, + size_t /*argumentCount*/, + const JSValueRef /*arguments*/[], + JSValueRef* /*exception*/) +{ + LogDebug("widget constructor"); + return JSObjectMake(context, JSWidget::getClassRef(), NULL); +} + +#undef CATCH_EXCEPTION_NO_MODIFABLE +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +#undef CATCH_EXCEPTION_OUT_OF_RANGE +#undef CATCH_EXCEPTION_INVALID_ARG +} +} diff --git a/src_mobile/standards/W3C/Widget/JSWidget.h b/src_mobile/standards/W3C/Widget/JSWidget.h new file mode 100644 index 0000000..f1f979c --- /dev/null +++ b/src_mobile/standards/W3C/Widget/JSWidget.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSWidget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_WIDGET_H_ +#define _WRT_PLUGIN_JS_WIDGET_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +class JSWidget +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + static JSObjectRef callAsConstructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getAuthor(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAuthorEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAuthorHref(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getShortName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getHeight(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getWidth(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; +} +} + +#endif /* _WRT_PLUGIN_JS_WIDGET_INTERFACE_H_ */ diff --git a/src_mobile/standards/W3C/Widget/plugin_config.cpp b/src_mobile/standards/W3C/Widget/plugin_config.cpp new file mode 100644 index 0000000..8588aca --- /dev/null +++ b/src_mobile/standards/W3C/Widget/plugin_config.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "plugin_config.h" + +namespace WrtPlugins { +namespace W3C { +template <> +WidgetDeclarations::ParamsMap WidgetDeclarations::m_params = + WrtPlugins::W3C::WidgetDeclarations::ParamsMap(); + +template <> +WidgetDeclarations::DeviceCapsMaps WidgetDeclarations::m_deviceCaps = + WrtPlugins::W3C::WidgetDeclarations::DeviceCapsMaps(); + +template <> +WidgetDeclarations::FeaturesMap WidgetDeclarations::m_features = { + { + "http://w3cWidgetInterface.com/w3c-widget-interface", + {} + } +}; + +template <> +WidgetDeclarations::FunctionsMap WidgetDeclarations::m_functions = + WrtPlugins::W3C::WidgetDeclarations::FunctionsMap(); +} // namespace Wac2_0 +} // namespace WrtPlugins diff --git a/src_mobile/standards/W3C/Widget/plugin_config.h b/src_mobile/standards/W3C/Widget/plugin_config.h new file mode 100644 index 0000000..13de247 --- /dev/null +++ b/src_mobile/standards/W3C/Widget/plugin_config.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef _WIDGET_PLUGIN_CONFIG_H_ +#define _WIDGET_PLUGIN_CONFIG_H_ + +#include + +namespace WrtPlugins { +namespace W3C { +enum class WidgetParamId +{}; + +enum class WidgetDeviceCapId +{}; + +enum class WidgetFunctionId +{}; + +typedef WrtDeviceApis::CommonsJavaScript::StaticDeclarations < + WidgetParamId, + WidgetDeviceCapId, + WidgetFunctionId> WidgetDeclarations; +} +} + +#endif // _WIDGET_PLUGIN_CONFIG_H_ diff --git a/src_mobile/standards/W3C/Widget/plugin_initializer.cpp b/src_mobile/standards/W3C/Widget/plugin_initializer.cpp new file mode 100644 index 0000000..1768069 --- /dev/null +++ b/src_mobile/standards/W3C/Widget/plugin_initializer.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file plugin_initializer.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include + +#include +#include + +#include "JSWidget.h" +#include "JSPreferences.h" + +#include "plugin_config.h" + +#define OBJECT_WIDGET "widget" +#define INTERFACE_WIDGET_NAME "Widget" +#define OBJECT_PREFERENCES "preferences" + +using namespace WrtPlugins::W3C; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace Options { +class_definition_options_t WidgetOptions = { + JS_CLASS, + CREATE_INSTANCE, + NONE_NOTICE, + IGNORED, + NULL, + NULL, + NULL +}; + +class_definition_options_t WidgetInterfaceOptions = { + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + IGNORED, //ignored + NULL, + NULL, + NULL +}; +}; + +void on_widget_init_callback(feature_mapping_interface_t *mapping) +{ + _D("[W3C\\widget] on_widget_init_callback"); + + WrtPlugins::W3C::WidgetDeclarations::getMappingInterface(mapping); +} + +void on_widget_start_callback(int widgetId) +{ + _D("[W3C\\widget] on_widget_start_callback (%d)", widgetId); + + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + _E("Wrt wrapper registration failed"); + return; + } +} + +void on_widget_stop_callback(int widgetId) +{ + _D("[W3C\\widget] on_widget_stop_callback (%d)", widgetId); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + _E("Wrt wrapper registration failed"); + return; + } +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_WIDGET_INIT(on_widget_init_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_GLOBAL, + INTERFACE_WIDGET_NAME, + (js_class_template_getter) WrtPlugins::W3C::JSWidget::getClassRef, + reinterpret_cast(WrtPlugins::W3C::JSWidget:: + callAsConstructor), + &Options::WidgetInterfaceOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE_PRODUCT( + WRT_JS_EXTENSION_OBJECT_GLOBAL, + OBJECT_WIDGET, + INTERFACE_WIDGET_NAME, + &Options::WidgetOptions) + +PLUGIN_CLASS_MAP_END + +#undef OBJECT_WIDGET +#undef OBJECT_PREFERENCES diff --git a/src_mobile/wrt-popup/CMakeLists.txt b/src_mobile/wrt-popup/CMakeLists.txt new file mode 100755 index 0000000..13a79cc --- /dev/null +++ b/src_mobile/wrt-popup/CMakeLists.txt @@ -0,0 +1,2 @@ +ADD_SUBDIRECTORY(ace) +ADD_SUBDIRECTORY(wrt) diff --git a/src_mobile/wrt-popup/ace/CMakeLists.txt b/src_mobile/wrt-popup/ace/CMakeLists.txt new file mode 100755 index 0000000..2ecd23d --- /dev/null +++ b/src_mobile/wrt-popup/ace/CMakeLists.txt @@ -0,0 +1,2 @@ +ADD_SUBDIRECTORY(popup-bin) +ADD_SUBDIRECTORY(popup-runner) diff --git a/src_mobile/wrt-popup/ace/popup-bin/CMakeLists.txt b/src_mobile/wrt-popup/ace/popup-bin/CMakeLists.txt new file mode 100644 index 0000000..f87483d --- /dev/null +++ b/src_mobile/wrt-popup/ace/popup-bin/CMakeLists.txt @@ -0,0 +1,64 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Janusz Kozerski (j.kozerski@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_DEP + dpl-efl + elementary + security-client + security-popup-validation + REQUIRED) + +set(WRT_POPUP_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/ace/popup-bin) + +set(WRT_POPUP_SOURCES + ${WRT_POPUP_SRC_DIR}/Popup.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_SRC_DIR} + ${WRT_POPUP_DEP_INCLUDE_DIRS} +) + +ADD_EXECUTABLE(${TARGET_POPUP_ACE} + ${WRT_POPUP_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + #LINK_FLAGS "-Wl,--as-needed -Wl" + SOVERSION ${PROJECT_API_VERSION} + VERSION ${PROJECT_VERSION} +) + +target_link_libraries(${TARGET_POPUP_ACE} + ${WRT_POPUP_DEP_LIBRARIES} + ${TARGET_POPUP_ACE_RUNNER_LIB} + ${WRT_POPUP_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_ACE} + DESTINATION bin +) diff --git a/src_mobile/wrt-popup/ace/popup-bin/Popup.cpp b/src_mobile/wrt-popup/ace/popup-bin/Popup.cpp new file mode 100644 index 0000000..6d51ace --- /dev/null +++ b/src_mobile/wrt-popup/ace/popup-bin/Popup.cpp @@ -0,0 +1,463 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file Popup.c + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +/* + * This is just a example pop-up that shows how to use a new C-API in + * wrt-security. + * This pop-up should be re-implemented by members of NGWAP. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "popup-runner.h" +#include "Popup.h" + +namespace { // anonymous +static void set_validity_from_checkbox(struct ace_popup_data *pdp) +{ + if (NULL == pdp) { + LogError("pdp is NULL; return"); + return; + } + + if (pdp->always) { + LogDebug("Remember ALWAYS"); + pdp->remember_choice = ACE_ALWAYS; + return; + } + if (pdp->per_session) { + LogDebug("Remember PER_SESSION"); + pdp->remember_choice = ACE_PER_SESSION; + return; + } + LogDebug("Remember ONCE"); + pdp->remember_choice = ACE_ONCE; + return; +} + +static void on_done(void) +{ + // Quit the efl-mainloop + LogDebug("elm_exit()"); + elm_exit(); +} + +static void grant_answer(void *data, + Evas_Object * /* obj */, + void * /* event_info */) +{ + LogDebug("grant_answer"); + if (NULL == data) { + LogError("data is NULL; return"); + return; + } + struct ace_popup_data *pdp = static_cast (data); + + set_validity_from_checkbox(pdp); + + ace_popup_validation_initialize(); + pdp->validation_return = ace_validate_answer( + ACE_TRUE, + pdp->remember_choice, + pdp->resource_name, + pdp->session_id, + &(pdp->param_list), + pdp->handle, + &(pdp->validation_result)); + ace_popup_validation_shutdown(); + + on_done(); +} + +static void deny_answer(void *data, + Evas_Object * /* obj */, + void * /* event_info */) +{ + LogDebug("deny_answer"); + if (NULL == data) { + LogError("data is NULL; return"); + return; + } + struct ace_popup_data *pdp = static_cast (data); + + set_validity_from_checkbox(pdp); + + ace_popup_validation_initialize(); + pdp->validation_return = ace_validate_answer( + ACE_FALSE, + pdp->remember_choice, + pdp->resource_name, + pdp->session_id, + &(pdp->param_list), + pdp->handle, + &(pdp->validation_result)); + ace_popup_validation_shutdown(); + + on_done(); +} + +static int _ace_params_deserializer(ace_param_list_t* ace_param_list, + Wrt::Popup::BinaryStream *stream) +{ + LogDebug("_ace_params_deserializer"); + + if (NULL == ace_param_list || NULL == stream) { + LogError("ace_param_list or stream is NULL; return -1"); + return -1; + } + + // deserialize ace_param_list->count; + size_t count = 0; + DPL::Deserialization::Deserialize(*stream, count); + ace_param_list->count = count; + LogDebug("count : " << count); + + std::string name; + std::string value; + if (count == 0) { + ace_param_list->items = NULL; + return 0; + } + ace_param_list->items = + static_cast (malloc(count * sizeof(ace_param_t))); + memset(ace_param_list->items, 0, count * sizeof(ace_param_t)); + + for (size_t i = 0; i < count; ++i) { + DPL::Deserialization::Deserialize(*stream, name); + ace_param_list->items[i].name = + strdup(const_cast (name.c_str())); + + DPL::Deserialization::Deserialize(*stream, value); + ace_param_list->items[i].value = + strdup(const_cast (value.c_str())); + } + return 0; +} + +static void _ace_params_finalize(ace_param_list_t* ace_param_list) +{ + if (!ace_param_list || !ace_param_list->items) { + LogDebug("List is null, nothing to do"); + return; + } + for (size_t i = 0; i < ace_param_list->count; ++i) { + free(ace_param_list->items[i].name); + free(ace_param_list->items[i].value); + } + free(ace_param_list->items); + ace_param_list->items = NULL; + ace_param_list->count = 0; +} + +static void show_popup(struct ace_popup_data *pdp) +{ + LogDebug("show_popup()"); + + if (NULL == pdp) { + LogError("pdp is NULL; return"); + return; + } + + const char *resource_type = static_cast (pdp->resource_name); + + Evas_Object *win = NULL; + Evas_Object *box = NULL; + Evas_Object *label = NULL; + Evas_Object *grant_button = NULL; + Evas_Object *deny_button = NULL; + pdp->per_session = EINA_FALSE; + pdp->always = EINA_FALSE; + + win = elm_win_add(NULL, "The wrt-client popup", ELM_WIN_NOTIFICATION); + elm_win_autodel_set(win, EINA_TRUE); + elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); + evas_object_show(win); + elm_win_indicator_opacity_set(win, ELM_WIN_INDICATOR_TRANSLUCENT); + + pdp->popup = elm_popup_add(win); + + box = elm_box_add(pdp->popup); + evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, 0); + evas_object_size_hint_align_set(box, EVAS_HINT_FILL, 0.0); + + label = elm_label_add(pdp->popup); + elm_object_style_set(label, "popup_description/default"); + elm_label_line_wrap_set(label, ELM_WRAP_MIXED); + char *buff = NULL; + if (-1 == + asprintf(&buff, "Application need an access to %s.
Grant or deny?", + resource_type)) + { + LogError("asprintf failed - returned -1"); + evas_object_del(label); + evas_object_del(pdp->popup); + evas_object_del(win); + return; + } + elm_object_text_set(label, buff); + free(buff); + evas_object_size_hint_weight_set(label, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(label, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(label); + elm_box_pack_end(box, label); + + LogDebug("popup_type == " << pdp->popup_type); + if (pdp->popup_type == ACE_SESSION || pdp->popup_type == ACE_BLANKET) { + LogDebug("popup_type == ACE_SESSION || ACE_BLANKET"); + Evas_Object *cb_session = elm_check_add(pdp->popup); + elm_object_text_set(cb_session, "Remember choice for this session"); + elm_check_state_pointer_set(cb_session, &(pdp->per_session)); + evas_object_smart_callback_add(cb_session, "changed", NULL, NULL); + evas_object_size_hint_align_set(cb_session, + EVAS_HINT_FILL, + EVAS_HINT_FILL); + evas_object_size_hint_weight_set(cb_session, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + evas_object_show(cb_session); + elm_box_pack_end(box, cb_session); + + if (pdp->popup_type == ACE_BLANKET) { + LogDebug("popup_type == ACE_BLANKET"); + Evas_Object *cb_always = elm_check_add(pdp->popup); + elm_object_text_set(cb_always, "Remember choice forever"); + elm_check_state_pointer_set(cb_always, &(pdp->always)); + evas_object_smart_callback_add(cb_always, "changed", NULL, NULL); + evas_object_size_hint_align_set(cb_always, + EVAS_HINT_FILL, + EVAS_HINT_FILL); + evas_object_size_hint_weight_set(cb_always, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + evas_object_show(cb_always); + elm_box_pack_end(box, cb_always); + } + } + + elm_object_part_content_set(pdp->popup, "default", box); + + grant_button = elm_button_add(pdp->popup); + elm_object_text_set(grant_button, "Grant"); + elm_object_part_content_set(pdp->popup, "button1", grant_button); + evas_object_smart_callback_add(grant_button, "clicked", grant_answer, pdp); + + deny_button = elm_button_add(pdp->popup); + elm_object_text_set(deny_button, "Deny"); + elm_object_part_content_set(pdp->popup, "button2", deny_button); + evas_object_smart_callback_add(deny_button, "clicked", deny_answer, pdp); + + evas_object_show(pdp->popup); + + // Showing the popup window + evas_object_show(win); + + // Run the efl mainloop + elm_run(); +} +} // anonymous + +EAPI_MAIN int +elm_main(int argc, char ** argv) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // int pipe_in and int pipe_out should be passed to Popup via args. + + // These parameters should be passed to Popup via pipe: + // ace_popup_t popup_type + // const ace_resource_t resource_name + // const ace_session_id_t session_id + // ace_widget_handle_t handle + // const ace_param_list_t param_list + + try { + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT-POPUP-BIN"); + } Catch(DPL::Exception) { + //cannot run logger + return ACE_INTERNAL_ERROR; + } + LogDebug( + "############################ popup binary ################################"); + + if (argc < 3) { + LogError( + "To few args passed in exec to popup-bin - should be at least 3:"); + LogError("(binary-name, pipe_in, pipe_out)"); + LogError("return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + LogDebug("Passed args: " << argv[0] << ", " << argv[1] << ", " << + argv[2]); + + int pipe_in; + int pipe_out; + std::stringstream parsing_stream; + + // Parsing args (pipe_in, pipe_out) + parsing_stream.str(argv[1]); + parsing_stream >> pipe_in; + if ( parsing_stream.fail() ) { + LogError("Error while parsing pipe_in; return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + parsing_stream.clear(); + parsing_stream.str(argv[2]); + parsing_stream >> pipe_out; + if ( parsing_stream.fail() ) { + LogError("Error while parsing pipe_out; return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + parsing_stream.clear(); + LogDebug("Parsed pipes: IN: " << pipe_in << ", OUT: " << pipe_out); + + int buff_size = 1024; + char line[buff_size]; + + struct ace_popup_data pd; + struct ace_popup_data *pdp = &pd; + + pdp->popup = NULL; + + ssize_t count = 0; + time_t time_start; + time(&time_start); // now + double timeout = 10.0; + // try to read parameters from pipe_in + // timeout is set for 10 seconds + do { + count = TEMP_FAILURE_RETRY(read(pipe_in, line, buff_size)); + if (timeout < difftime(time(NULL), time_start) ) { + LogError("Timeout reached! Exit popup - ACE_INTERNAL_ERROR"); + close(pipe_in); + close(pipe_out); + return ACE_INTERNAL_ERROR; + } + } while (0 == count); + if (count < 0) { + close(pipe_in); + close(pipe_out); + LogError("read returned a negative value (" << count << ")"); + LogError("errno: " << strerror(errno) ); + LogError("Exit popup - ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + LogDebug("Read bytes : " << count << " (in " << + difftime(time_start, time(NULL)) << " seconds)"); + close(pipe_in); // cleanup + + Wrt::Popup::BinaryStream stream; + stream.Write(count, static_cast (line)); + int popup_type = ACE_ONESHOT; + std::string resource_name_str; + std::string session_id_str; + int handle = 0; + + LogDebug("------- Deserialization -------"); + // Deserialization order: + // popup_type, resource_name, session_id, handle, param_list + + DPL::Deserialization::Deserialize(stream, popup_type); + LogDebug("popup_type_int : " << popup_type); + pdp->popup_type = static_cast (popup_type); + + DPL::Deserialization::Deserialize(stream, resource_name_str); + LogDebug("resource_name_char : " << resource_name_str.c_str()); + pdp->resource_name = + strdup(const_cast (resource_name_str.c_str())); + + DPL::Deserialization::Deserialize(stream, session_id_str); + LogDebug("session_id_char : " << session_id_str.c_str()); + pdp->session_id = + strdup(const_cast (session_id_str.c_str())); + + DPL::Deserialization::Deserialize(stream, handle); + LogDebug("handle_int : " << handle); + pdp->handle = static_cast (handle); + + if (_ace_params_deserializer(&(pdp->param_list), &stream)) { + return ACE_INTERNAL_ERROR; + } + + pdp->per_session = EINA_FALSE; + pdp->always = EINA_FALSE; + pdp->validation_return = ACE_ACE_UNKNOWN_ERROR; + + show_popup(pdp); // Showing popup + + // sending validation_result to popup-runner + Wrt::Popup::BinaryStream stream_out; + + LogDebug("pdp->validation_result : " << pdp->validation_result); + int validation_result_int = (int) pdp->validation_result; + LogDebug("validation_result_int : " << validation_result_int); + DPL::Serialization::Serialize(stream_out, validation_result_int); + if (-1 == + TEMP_FAILURE_RETRY(write(pipe_out, stream_out.char_pointer(), + stream_out.size()))) + { + LogError("Write to pipe failed!"); + close(pipe_out); + return ACE_INTERNAL_ERROR; + } + close(pipe_out); + + if (pdp->validation_return == ACE_OK) { + LogDebug("ACE_OK"); + } else if (pdp->validation_return == ACE_INVALID_ARGUMENTS) { + LogError("ACE_INVALID_ARGUMENTS"); + } else if (pdp->validation_return == ACE_INTERNAL_ERROR) { + LogError("ACE_INTERNAL_ERROR"); + } else if (pdp->validation_return == ACE_ACE_UNKNOWN_ERROR) { + LogError("ACE_ACE_UNKNOWN_ERROR"); + } else { + LogError("Really unknown error!!!"); + } + + LogDebug( + "############################ /popup binary ################################"); + + // Shutdown elementary + //LogDebug("elm_shutdown()"); + //elm_shutdown(); + // This is commented because, it causes that popup exits with 139 code + // (Segmentatation violation). + // Not calling elm_shutdown() should not have any negative consequences + // because this binary ends + // in next line, and system should clear the memory. + + _ace_params_finalize(&(pdp->param_list)); + return pdp->validation_return; + } + UNHANDLED_EXCEPTION_HANDLER_END +} +ELM_MAIN() diff --git a/src_mobile/wrt-popup/ace/popup-bin/Popup.h b/src_mobile/wrt-popup/ace/popup-bin/Popup.h new file mode 100644 index 0000000..388c921 --- /dev/null +++ b/src_mobile/wrt-popup/ace/popup-bin/Popup.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file Popup.h + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +#include +#include + +struct ace_popup_data { + ace_popup_t popup_type; + ace_resource_t resource_name; + ace_session_id_t session_id; + ace_param_list_t param_list; + ace_widget_handle_t handle; + ace_bool_t validation_result; + ace_return_t validation_return; + + Evas_Object *popup; + Eina_Bool per_session; + Eina_Bool always; + + ace_validity_t remember_choice; +}; diff --git a/src_mobile/wrt-popup/ace/popup-runner/CMakeLists.txt b/src_mobile/wrt-popup/ace/popup-runner/CMakeLists.txt new file mode 100644 index 0000000..4e5053c --- /dev/null +++ b/src_mobile/wrt-popup/ace/popup-runner/CMakeLists.txt @@ -0,0 +1,65 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Janusz Kozerski (j.kozerski@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_RUNNER_LIB_DEP + dpl-efl + elementary + security-client + REQUIRED) + +set(WRT_POPUP_RUNNER_LIB_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/ace/popup-runner) + +set(WRT_POPUP_RUNNER_LIB_SOURCES + ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/popup-runner.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_RUNNER_LIB_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_RUNNER_LIB_SRC_DIR} + ${WRT_POPUP_RUNNER_LIB_DEP_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_POPUP_ACE_RUNNER_LIB} SHARED + ${WRT_POPUP_RUNNER_LIB_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_POPUP_ACE_RUNNER_LIB} + ${WRT_POPUP_RUNNER_LIB_DEP_LIBRARIES} + ${WRT_POPUP_RUNNER_LIB_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_ACE_RUNNER_LIB} + DESTINATION lib +) + +INSTALL(FILES ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/popup-runner.h + DESTINATION ${DESTINATION_HEADERS_WRT_POPUP_RUNNER} +) diff --git a/src_mobile/wrt-popup/ace/popup-runner/popup-runner.cpp b/src_mobile/wrt-popup/ace/popup-runner/popup-runner.cpp new file mode 100644 index 0000000..e46fc16 --- /dev/null +++ b/src_mobile/wrt-popup/ace/popup-runner/popup-runner.cpp @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup-runner.cpp + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +/* + * This is just a example pop-up that shows how to use a new C-API in + * wrt-security. + * This pop-up should be re-implemented by members of NGWAP. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "popup-runner.h" + +namespace { // anonymous +const char *POPUP_EXEC = "/usr/bin/wrt-popup-ace-runtime"; + +void _ace_params_serializer (const ace_param_list_t* ace_param_list, + Wrt::Popup::BinaryStream *stream) +{ + LogDebug("_ace_params_serializer"); + + if (NULL == ace_param_list || NULL == stream) { + LogError("*ace_param_list or *stream is NULL; return"); + return; + } + LogDebug("Param count : " << ace_param_list->count); + + // serialize ace_param_list->count; + size_t count = static_cast (ace_param_list->count); + DPL::Serialization::Serialize(*stream, count); + + for (size_t i = 0; i < count; ++i) { + std::string name(ace_param_list->items[i].name); + DPL::Serialization::Serialize(*stream, name); + + std::string value(ace_param_list->items[i].value); + DPL::Serialization::Serialize(*stream, value); + } +} +} // anonymous namespace + +namespace Wrt { +namespace Popup { +// BinaryStream class implementation +void BinaryStream::Read(size_t num, void * bytes) +{ + size_t max_size = m_data.size(); + for (size_t i = 0; i < num; ++i) { + if (i + m_readPosition >= max_size) { + return; + } + static_cast (bytes)[i] = m_data[i + m_readPosition]; + } + m_readPosition += num; +} + +void BinaryStream::Write(size_t num, const void * bytes) +{ + for (size_t i = 0; i < num; ++i) { + m_data.push_back(static_cast (bytes)[i]); + } +} + +BinaryStream::BinaryStream() +{ + m_readPosition = 0; +} + +BinaryStream::~BinaryStream() {} + +const unsigned char* BinaryStream::char_pointer() const +{ + return &m_data[0]; +} + +size_t BinaryStream::size() const +{ + return m_data.size(); +} +// BinaryStream + +ace_return_t run_popup( + ace_popup_t popup_type, + const ace_resource_t resource_name, + const ace_session_id_t session_id, + const ace_param_list_t* ace_param_list, + ace_widget_handle_t handle, + ace_bool_t* validation_result) +{ + if (NULL == resource_name || + NULL == session_id || + NULL == ace_param_list || + NULL == validation_result) + { + LogError("run_popup : ACE_INVALID_ARGUMENTS"); + return ACE_INVALID_ARGUMENTS; + } + LogDebug("popup_type : " << popup_type); + LogDebug("resource_name : " << resource_name); + LogDebug("session_id : " << session_id); + LogDebug("widget handle : " << handle); + + int popup_type_int = static_cast (popup_type); + char *resource_name_char = static_cast (resource_name); + char *session_id_char = static_cast (session_id); + int handle_int = static_cast (handle); + + // serialization + Wrt::Popup::BinaryStream stream; + DPL::Serialization::Serialize(stream, popup_type_int); + + std::string resource_name_str(resource_name_char); + DPL::Serialization::Serialize(stream, resource_name_str); + + std::string session_id_str(session_id_char); + DPL::Serialization::Serialize(stream, session_id_str); + + DPL::Serialization::Serialize(stream, handle_int); + + _ace_params_serializer(ace_param_list, &stream); + + int fd_send_to_child[2]; + int fd_send_to_parent[2]; + pid_t childpid; + + if (0 != pipe(fd_send_to_child)) { + LogError("Cannot create pipes!"); + return ACE_INTERNAL_ERROR; + } + if (0 != pipe(fd_send_to_parent)) { + LogError("Cannot create pipes!"); + return ACE_INTERNAL_ERROR; + } + + if ((childpid = fork()) == -1) { + LogError("Fork() ERROR"); + return ACE_ACE_UNKNOWN_ERROR; + } + + if (childpid == 0) { // Child process + LogDebug("Child"); + + // read data from parent + close(fd_send_to_child[1]); + + // send data to parent + close(fd_send_to_parent[0]); + + std::stringstream pipe_in_buff; + std::stringstream pipe_out_buff; + pipe_in_buff << fd_send_to_parent[1]; + pipe_out_buff << fd_send_to_child[0]; + std::string pipe_in = pipe_in_buff.str(); + std::string pipe_out = pipe_out_buff.str(); + + LogDebug( + "Passed file descriptors: " << fd_send_to_child[0] << ", " << + fd_send_to_parent[1]); + + if (execl(POPUP_EXEC, POPUP_EXEC, pipe_out.c_str(), pipe_in.c_str(), + NULL) < 0) + { + LogError("execlp FAILED"); + } + + LogError("This should not happened!!!"); + } // end of child process - from now you can use DEBUG LOGS + else { // Parent process + LogDebug("Parent"); + + int buff_size = 1024; + char result[buff_size]; + // send data to child + close(fd_send_to_child[0]); + + //writing to child + LogDebug("Sending message to popup-bin process"); + if (-1 == + TEMP_FAILURE_RETRY(write(fd_send_to_child[1], stream.char_pointer(), + stream.size()))) + { + LogError("Write to pipe failed!"); + return ACE_INTERNAL_ERROR; + } + close(fd_send_to_child[1]); // cleanup + LogDebug("Message has been sent"); + + // read data from child + close(fd_send_to_parent[1]); + + int status; + wait(&status); + LogDebug("STATUS EXIT ON POPUP (CHILD): " << status); + switch (status) { + case ACE_OK: + LogDebug("ACE_OK"); + break; + + case ACE_INVALID_ARGUMENTS: + LogDebug("ACE_INVALID_ARGUMENTS"); + close(fd_send_to_parent[0]); + return static_cast (status); + break; + + case ACE_INTERNAL_ERROR: + LogDebug("ACE_INTERNAL_ERROR"); + close(fd_send_to_parent[0]); + return static_cast (status); + break; + + case ACE_ACE_UNKNOWN_ERROR: + LogDebug("ACE_ACE_UNKNOWN_ERROR"); + close(fd_send_to_parent[0]); + return static_cast (status); + break; + + default: + LogDebug("UNKNOWN_ERROR"); + close(fd_send_to_parent[0]); + status = (int) ACE_ACE_UNKNOWN_ERROR; + return static_cast (status); + break; + } + + int count; + count = TEMP_FAILURE_RETRY(read(fd_send_to_parent[0], result, buff_size)); + close(fd_send_to_parent[0]); // cleanup + + + if (0 < count) { + BinaryStream stream_in; + int validation_result_int; + stream_in.Write(count, result); + LogDebug("RESULT FROM POPUP (CHILD) : [ " << count << " ]"); + DPL::Deserialization::Deserialize(stream_in, validation_result_int); + *validation_result = static_cast (validation_result_int); + + LogDebug("validation_result :"); + switch (*validation_result) { + case ACE_FALSE: + LogDebug("ACE_FALSE"); + break; + case ACE_TRUE: + LogDebug("ACE_TRUE"); + break; + default: + LogDebug("UNKNOWN - DEFAULT"); + break; + } + } else { + LogDebug("count = " << count); + LogDebug("UNKNOWN_ERROR"); + return ACE_ACE_UNKNOWN_ERROR; + } + + LogDebug("popup-runner: EXIT"); + return (ace_return_t) status; + } + + LogError("This should not happend!!!"); + return ACE_ACE_UNKNOWN_ERROR; +} +} // Popup +} // Wrt diff --git a/src_mobile/wrt-popup/ace/popup-runner/popup-runner.h b/src_mobile/wrt-popup/ace/popup-runner/popup-runner.h new file mode 100644 index 0000000..d136fb1 --- /dev/null +++ b/src_mobile/wrt-popup/ace/popup-runner/popup-runner.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup-runner.h + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +#include +#include + +#include + +namespace Wrt { +namespace Popup { +class BinaryStream : public DPL::IStream +{ + public: + void Read (size_t num, void * bytes); + void Write(size_t num, const void * bytes); + + BinaryStream(); + ~BinaryStream(); + + const unsigned char* char_pointer() const; + size_t size() const; + + private: + std::vector m_data; + size_t m_readPosition; +}; + +ace_return_t run_popup( + ace_popup_t popup_type, + const ace_resource_t resource_name, + const ace_session_id_t session_id, + const ace_param_list_t* ace_param_list, + ace_widget_handle_t handle, + ace_bool_t* validation_result + ); +} // Popup +} // Wrt diff --git a/src_mobile/wrt-popup/wrt/CMakeLists.txt b/src_mobile/wrt-popup/wrt/CMakeLists.txt new file mode 100755 index 0000000..ed0e24b --- /dev/null +++ b/src_mobile/wrt-popup/wrt/CMakeLists.txt @@ -0,0 +1,9 @@ + +set(WRT_POPUP_COMMON_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/wrt) + +SET(WRT_POPUP_COMMON_SRCS + ${WRT_POPUP_COMMON_DIR}/PopupSerializer.cpp +) + +ADD_SUBDIRECTORY(popup-bin) +ADD_SUBDIRECTORY(popup-runner) diff --git a/src_mobile/wrt-popup/wrt/PopupEnum.h b/src_mobile/wrt-popup/wrt/PopupEnum.h new file mode 100644 index 0000000..3200ef4 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/PopupEnum.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_ENUM_H +#define WRT_POPUP_ENUM_H + +namespace Wrt { +enum PopupType { + INFO_PROMPT = 1, + YES_NO_PROMPT, + YES_NO_CHECK_PROMPT +}; +} + +#endif + diff --git a/src_mobile/wrt-popup/wrt/PopupSerializer.cpp b/src_mobile/wrt-popup/wrt/PopupSerializer.cpp new file mode 100644 index 0000000..e9dd99f --- /dev/null +++ b/src_mobile/wrt-popup/wrt/PopupSerializer.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "PopupSerializer.h" + +#include + +namespace Wrt { +namespace PopupSerializer { +void appendArg(int arg, DPL::BinaryQueue &buffer) +{ + size_t argSize = sizeof(arg); + buffer.AppendCopy(&argSize, sizeof(argSize)); + buffer.AppendCopy(&arg, sizeof(arg)); +} + +void appendArg(const std::string &arg, DPL::BinaryQueue &buffer) +{ + size_t argSize = arg.size(); + buffer.AppendCopy(&argSize, sizeof(argSize)); + buffer.AppendCopy(arg.c_str(), argSize); +} + +int getIntArg(DPL::BinaryQueue &buffer) +{ + int result; + size_t argSize; + buffer.FlattenConsume(&argSize, sizeof(argSize)); + buffer.FlattenConsume(&result, argSize); + //TODO: what if argSize != sizeof(int) + //This should not be problem if this is run on the same machine. + return result; +} + +std::string getStringArg(DPL::BinaryQueue &buffer) +{ + std::string::size_type size; + buffer.FlattenConsume(&size, sizeof(size)); + std::unique_ptr str(new char[size]); + buffer.FlattenConsume(str.get(), size); + return std::string(str.get(), str.get() + size); +} +} +} // Wrt diff --git a/src_mobile/wrt-popup/wrt/PopupSerializer.h b/src_mobile/wrt-popup/wrt/PopupSerializer.h new file mode 100644 index 0000000..70407ec --- /dev/null +++ b/src_mobile/wrt-popup/wrt/PopupSerializer.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_SERIALIZER_H +#define WRT_POPUP_SERIALIZER_H + +#include +#include + +namespace Wrt { +namespace PopupSerializer { +void appendArg(int arg, DPL::BinaryQueue &buffer); +void appendArg(const std::string &arg, DPL::BinaryQueue &buffer); + +int getIntArg(DPL::BinaryQueue &buffer); +std::string getStringArg(DPL::BinaryQueue &buffer); +} +} // Wrt + +#endif \ No newline at end of file diff --git a/src_mobile/wrt-popup/wrt/popup-bin/CMakeLists.txt b/src_mobile/wrt-popup/wrt/popup-bin/CMakeLists.txt new file mode 100644 index 0000000..52f73ff --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/CMakeLists.txt @@ -0,0 +1,56 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +PKG_CHECK_MODULES(WRT_POPUP_DEPS + ecore-x + dpl-efl + dpl-event-efl + REQUIRED +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/renderer + ${WRT_POPUP_DEPS_INCLUDE_DIRS} + ${WRT_POPUP_COMMON_DIR} +) + +SET(WRT_POPUP_SRCS + ${WRT_POPUP_COMMON_SRCS} + wrt-popup.cpp + YesNoPopup.cpp + YesNoCheckPopup.cpp + InfoPopup.cpp + renderer/evas_object.cpp + renderer/popup_controller.cpp + renderer/popup_manager.cpp + renderer/popup_renderer.cpp +) + +ADD_EXECUTABLE(${TARGET_POPUP_WRT} + ${WRT_POPUP_SRCS} +) + +TARGET_LINK_LIBRARIES(${TARGET_POPUP_WRT} + ${WRT_POPUP_DEPS_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT} PROPERTIES + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON +) + +INSTALL(TARGETS ${TARGET_POPUP_WRT} DESTINATION bin) diff --git a/src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.cpp b/src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.cpp new file mode 100644 index 0000000..4536350 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file InfoPopup.cpp + * @author Lukasz Marek(l.marek@samsung.com) + * @version 1.0 + * @brief Popup that displays information. Inplementation + */ + +#include "InfoPopup.h" +#include +#include +#include "popup_manager.h" +#include "popup.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +InfoPopup::InfoPopup() : + m_parent(NULL) +{} + +void InfoPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) +{ + LogDebug("Entered"); + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + std::string button = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + LogDebug("title: " << title << " message: " << message); + + m_parent = parent; + + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + + popup->Append(new Renderer::PopupObject::Button(button, 0)); + + ListenForAnswer(popup); + + Renderer::ShowPopupEventShort event(popup, + MakeAnswerCallback( + this, + &InfoPopup::responseCallback)); + + CONTROLLER_POST_EVENT(Renderer::PopupController, + event); + + LogDebug("Exited"); + return; +} + +void InfoPopup::responseCallback(const Renderer::AnswerCallbackData &answer) +{ + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(answer.buttonAnswer, retValue); + m_parent->response(retValue); +} +} // Popup +} // Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.h b/src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.h new file mode 100644 index 0000000..3a29fc0 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/InfoPopup.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file InfoPopup.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons + */ + +#ifndef WRT_INFO_POPUP_H +#define WRT_INFO_POPUP_H + +#include "wrt-popup.h" + +namespace Wrt { +namespace Popup { +class InfoPopup : public IPopup +{ + public: + InfoPopup(); + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent); + + private: + + void responseCallback(const Renderer::AnswerCallbackData &answer); + WrtPopup* m_parent; +}; +} // Popup +} // Wrt + +#endif /* WRT_INFO_POPUP_H */ + diff --git a/src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp b/src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp new file mode 100644 index 0000000..7cdbf73 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp @@ -0,0 +1,51 @@ +/* + * File: YesNoCheckPopup.cpp + * Author: pciezkowski + * + * Created on December 12, 2012, 9:23 AM + */ + +#include "YesNoCheckPopup.h" +#include +#include +#include "popup_manager.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +YesNoCheckPopup::~YesNoCheckPopup() +{} + +Renderer::CtrlPopupPtr YesNoCheckPopup::createPopup( + DPL::BinaryQueueAutoPtr data) +{ + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + std::string checkboxLabel = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + LogDebug("title: " << title << " message: " << message << " checkbox: " << + checkboxLabel); + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + popup->Append(new Renderer::PopupObject::Check(checkboxLabel)); + popup->Append(new Renderer::PopupObject::Button(YES_LABEL, POPUP_YES_VALUE)); + popup->Append(new Renderer::PopupObject::Button(NO_LABEL, POPUP_NO_VALUE)); + return popup; +} + +void YesNoCheckPopup::responseCallback( + const Renderer::AnswerCallbackData &answer) +{ + bool result = (POPUP_YES_VALUE == answer.buttonAnswer); + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(result, retValue); + LogDebug("Check state: " << answer.chackState); + PopupSerializer::appendArg(answer.chackState, retValue); + m_parent->response(retValue); +} +} // Popup +} // Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h b/src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h new file mode 100644 index 0000000..9012df5 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file YesNoCheckPopup.cpp + * @author Przmeyslaw Ciezkowsko (p.ciezkowski@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons and checkbox. + * Inplementation + */ + +#include "YesNoPopup.h" +#include "wrt-popup.h" + +#ifndef WRT_YES_NO_CHECK_POPUP_H +#define WRT_YES_NO_CHECK_POPUP_H + +namespace Wrt { +namespace Popup { +class YesNoCheckPopup : public YesNoPopup +{ + public: + virtual ~YesNoCheckPopup(); + + protected: + virtual Renderer::CtrlPopupPtr createPopup(DPL::BinaryQueueAutoPtr data); + virtual void responseCallback(const Renderer::AnswerCallbackData &answer); +}; +} // Popup +} // Wrt + +#endif /* WRT_YES_NO_CHECK_POPUP_H */ + diff --git a/src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.cpp b/src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.cpp new file mode 100644 index 0000000..a47d205 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file YesNoPopup.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons. Inplementation + */ + +#include "YesNoPopup.h" +#include +#include +#include "popup_manager.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +void YesNoPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) +{ + LogDebug("Entered"); + m_parent = parent; + Renderer::CtrlPopupPtr popup = createPopup(data); + ListenForAnswer(popup); + + Renderer::ShowPopupEventShort event(popup, + MakeAnswerCallback( + this, + &YesNoPopup::responseCallback)); + + CONTROLLER_POST_EVENT(Renderer::PopupController, + event); + + LogDebug("Exited"); + return; +} + +void YesNoPopup::responseCallback(const Renderer::AnswerCallbackData &answer) +{ + bool result = (POPUP_YES_VALUE == answer.buttonAnswer); + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(result, retValue); + m_parent->response(retValue); +} + +YesNoPopup::~YesNoPopup() +{} + +Renderer::CtrlPopupPtr YesNoPopup::createPopup(DPL::BinaryQueueAutoPtr data) +{ + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + LogDebug("title: " << title << " message: " << message); + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + + popup->Append(new Renderer::PopupObject::Button(YES_LABEL, POPUP_YES_VALUE)); + popup->Append(new Renderer::PopupObject::Button(NO_LABEL, POPUP_NO_VALUE)); + return popup; +} +} // Popup +} // Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.h b/src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.h new file mode 100644 index 0000000..5dbe2f8 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/YesNoPopup.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file YesNoPopup.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons + */ + +#ifndef WRT_YES_NO_POPUP_H +#define WRT_YES_NO_POPUP_H + +#include "wrt-popup.h" + +namespace Wrt { +namespace Popup { +const char YES_LABEL[] = "Yes"; +const char NO_LABEL[] = "No"; +const int POPUP_YES_VALUE = 1; +const int POPUP_NO_VALUE = 2; + +class YesNoPopup : public IPopup +{ + public: + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent); + virtual ~YesNoPopup(); + + protected: + virtual Renderer::CtrlPopupPtr createPopup(DPL::BinaryQueueAutoPtr data); + virtual void responseCallback(const Renderer::AnswerCallbackData &answer); + WrtPopup* m_parent; +}; +} // Popup +} // Wrt + +#endif /* WRT_YES_NO_POPUP_H */ + diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp b/src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp new file mode 100644 index 0000000..13b38c1 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file evas_object.cpp + * @author Lukasz Wrzosek (l.wrzosel@samsung.com) + * @version 1.0 + * @brief This file is the implementation for Evas_Object wrapper from + * Efl. + */ + +#include "evas_object.h" +#include +#include + +namespace Wrt { +namespace Popup { +namespace Renderer { +Evas_Object* EvasObject::IConnection::GetEvasObject() +{ + return m_object->GetObject(); +} + +void EvasObject::IConnection::Disconnect() +{ + m_object->DisconnectCallback(this); +} + +EvasObject::IConnection::IConnection(EvasObject::EvasObjectShared* object) : + m_object(object) +{} + +void EvasObject::IConnection::SmartCallbackWrapper(void* data, + Evas_Object* /*object*/, + void* event_info) +{ + Assert(data); + IConnection* Calle = static_cast(data); + Calle->Call(event_info); +} + +void EvasObject::IConnection::EvasCallbackWrapper(void* data, + Evas* /*evas*/, + Evas_Object* /*object*/, + void* event_info) +{ + Assert(data); + IConnection* Calle = static_cast(data); + Calle->Call(event_info); +} + +Evas_Object* EvasObject::EvasObjectShared::GetObject() +{ + return m_object; +} + +EvasObject::EvasObjectShared::SmartConnectionBase::SmartConnectionBase( + const std::string& name, + EvasObject::EvasObjectShared* object) : + IConnection(object), + m_callbackName(name) +{} + +void EvasObject::EvasObjectShared::SmartConnectionBase::ConnectPrv() +{ + evas_object_smart_callback_add(GetEvasObject(), + m_callbackName.c_str(), + &IConnection::SmartCallbackWrapper, this); +} + +void EvasObject::EvasObjectShared::SmartConnectionBase::DisconnectPrv() +{ + evas_object_smart_callback_del(GetEvasObject(), + m_callbackName.c_str(), + &IConnection::SmartCallbackWrapper); +} + +EvasObject::EvasObjectShared::EvasConnectionBase::EvasConnectionBase( + Evas_Callback_Type type, + EvasObject::EvasObjectShared* object) : + IConnection(object), + m_callbackType(type) +{} + +void EvasObject::EvasObjectShared::EvasConnectionBase::ConnectPrv() +{ + evas_object_event_callback_add( + GetEvasObject(), m_callbackType, &IConnection::EvasCallbackWrapper, + this); +} + +void EvasObject::EvasObjectShared::EvasConnectionBase::DisconnectPrv() +{ + evas_object_event_callback_del_full( + GetEvasObject(), m_callbackType, &IConnection::EvasCallbackWrapper, + this); +} + +EvasObject::EvasObjectShared::EvasObjectShared() : + m_object(NULL) +{} + +EvasObject::EvasObjectShared::EvasObjectShared(Evas_Object* object) : + m_object(object) +{ + Assert(m_object); + evas_object_event_callback_add(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent, + this); +} + +void EvasObject::EvasObjectShared::SetObject(Evas_Object* object) +{ + Assert(m_object == NULL); + Assert(object != NULL); + m_object = object; + evas_object_event_callback_add(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent, + this); +} + +EvasObject::EvasObjectShared::~EvasObjectShared() +{ + if (m_object) { + DisconnectAll(); + evas_object_event_callback_del(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent); + m_object = NULL; + } +} + +bool EvasObject::EvasObjectShared::DisconnectCallback(IConnection* connection) +{ + IConnectionsSet::iterator it = m_connections.find(connection); + if (it != m_connections.end()) { + (*it)->DisconnectPrv(); + delete connection; + m_connections.erase(it); + return true; + } + return false; +} + +void EvasObject::EvasObjectShared::DisconnectAll() +{ + FOREACH(it, m_connections) + { + (*it)->DisconnectPrv(); + delete *it; + } + m_connections.clear(); +} + +void EvasObject::EvasObjectShared::StaticOnDelEvent(void* data, + Evas* /*e*/, + Evas_Object* /*o*/, + void* /*ev*/) +{ + Assert(data); + EvasObjectShared* This = static_cast(data); + if (This->m_object) { + evas_object_event_callback_del(This->m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent); + This->DisconnectAll(); + This->m_object = NULL; + } +} + +EvasObject::EvasObject() : + m_object(new EvasObjectShared()) +{} + +EvasObject::EvasObject(Evas_Object* object) : + m_object(new EvasObjectShared(object)) +{} + +EvasObject::EvasObject(const EvasObject& other) : + m_object(other.m_object) +{} + +//this destructor must be here to let pimpl with shared_ptr work without warning +EvasObject::~EvasObject() +{} + +EvasObject& EvasObject::operator=(const EvasObject& other) +{ + Assert(m_object); + m_object = other.m_object; + return *this; +} + +EvasObject* EvasObject::operator=(Evas_Object* object) +{ + Assert(m_object); + m_object->SetObject(object); + return this; +} + +bool EvasObject::DisconnectCallback(IConnection* connection) +{ + Assert(m_object); + return m_object->DisconnectCallback(connection); +} + +void EvasObject::DisconnectAll() +{ + Assert(m_object); + m_object->DisconnectAll(); +} + +EvasObject::operator Evas_Object *() +{ + Assert(m_object); + return m_object->GetObject(); +} +} +} // namespace DPL +} // namespace Popup diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.h b/src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.h new file mode 100644 index 0000000..2758fa1 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/evas_object.h @@ -0,0 +1,654 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file evas_object.h + * @author Lukasz Wrzosek (l.wrzosel@samsung.com) + * @version 1.0 + * @brief This file is the header for Evas_Object wrapper from Efl. + */ + +#ifndef WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H +#define WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Wrt { +namespace Popup { +namespace Renderer { +class EvasObject +{ + class EvasObjectShared; + typedef std::shared_ptr EvasObjectSharedPtr; + + public: + class IConnection + { + public: + Evas_Object* GetEvasObject(); + void Disconnect(); + + private: + IConnection(EvasObjectShared* object); + virtual ~IConnection() + {} + virtual void Call(void* /*event_info*/) = 0; + + static void SmartCallbackWrapper(void* data, + Evas_Object* /*object*/, + void* event_info); + static void EvasCallbackWrapper(void* data, + Evas* /*evas*/, + Evas_Object* /*object*/, + void* event_info); + + virtual void ConnectPrv() = 0; + virtual void DisconnectPrv() = 0; + + friend class EvasObjectShared; + + EvasObjectShared* m_object; + }; + + private: + class EvasObjectShared : DPL::Noncopyable + { + public: + friend class IConnection; + Evas_Object* GetObject(); + + typedef std::set IConnectionsSet; + + class SmartConnectionBase : public IConnection + { + public: + SmartConnectionBase(const std::string& name, + EvasObjectShared* object); + + virtual void ConnectPrv(); + virtual void DisconnectPrv(); + std::string m_callbackName; + }; + + template + class SmartConnection : public SmartConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, + void* event_info, + Args ... args); + + SmartConnection(const std::string& name, + CbType callback, + EvasObjectShared* object, + Args ... args) : + SmartConnectionBase(name, object), + m_callback(callback), + m_args(args ...) + {} + + virtual ~SmartConnection() + {} + + virtual void Call(void* event_info) + { + DPL::Apply(m_callback, + m_args, + this, + event_info); + } + + private: + CbType m_callback; + std::tuple m_args; + }; + + template + class SmartMemberConnection1 : public SmartConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1); + + SmartMemberConnection1(const std::string& name, + CbType callback, + ThisType* callee, + ArgType1* arg1, + EvasObjectShared* object) : + SmartConnectionBase(name, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1) + {} + + virtual ~SmartMemberConnection1() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + }; + + template + class SmartMemberConnection2 : public SmartConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1, + ArgType2* arg2); + + SmartMemberConnection2(const std::string& name, + CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + SmartConnectionBase(name, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~SmartMemberConnection2() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + class EvasConnectionBase : public IConnection + { + public: + EvasConnectionBase(Evas_Callback_Type type, + EvasObjectShared* object); + + virtual void ConnectPrv(); + virtual void DisconnectPrv(); + + Evas_Callback_Type m_callbackType; + }; + + template + class EvasConnection1 : public EvasConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, void* event_info, + ArgType1 *arg1); + + EvasConnection1(Evas_Callback_Type type, + CbType callback, + ArgType1* arg1, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_arg1(arg1) + {} + + virtual ~EvasConnection1() + {} + + virtual void Call(void* event_info) + { + m_callback(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ArgType1* m_arg1; + }; + + template + class EvasConnection2 : public EvasConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, void* event_info, + ArgType1 *arg1, ArgType2 *arg2); + + EvasConnection2(Evas_Callback_Type type, + CbType callback, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~EvasConnection2() + {} + + virtual void Call(void* event_info) + { + m_callback(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + template + class EvasMemberConnection1 : public EvasConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1); + + EvasMemberConnection1(Evas_Callback_Type type, + CbType callback, + ThisType* callee, + ArgType1* arg1, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1) + {} + + virtual ~EvasMemberConnection1() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + }; + + template + class EvasMemberConnection2 : public EvasConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1* arg1, + ArgType2* arg2); + + EvasMemberConnection2(Evas_Callback_Type type, + CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~EvasMemberConnection2() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + EvasObjectShared(); + explicit EvasObjectShared(Evas_Object* object); + void SetObject(Evas_Object* object); + ~EvasObjectShared(); + + template + IConnection* ConnectSmartCallback( + const char* callbackName, + typename SmartConnection:: + CbType callback, + Args ... args) + { + Assert(m_object); + Assert(callbackName); + Assert(callback); + IConnection* connection = new SmartConnection( + callbackName, + callback, + this, + args ...); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename SmartMemberConnection2::CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callbackName); + Assert(callback); + IConnection* connection = + new SmartMemberConnection2( + callbackName, + callback, + callee, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename SmartMemberConnection1::CbType callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callbackName); + Assert(callback); + IConnection* connection = + new SmartMemberConnection1(callbackName, + callback, + callee, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectEvasCallback(Evas_Callback_Type callbackType, + typename EvasConnection2:: + CbType callback, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callbackType); + Assert(callback); + IConnection* connection = new EvasConnection2( + callbackType, + callback, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasConnection1:: + CbType callback, + ArgType1* arg1) + { + Assert(m_object); + Assert(callbackType); + Assert(callback); + IConnection* connection = new EvasConnection1( + callbackType, + callback, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasMemberConnection2::CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callbackType); + Assert(callback); + IConnection* connection = + new EvasMemberConnection2( + callbackType, + callback, + callee, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasMemberConnection1::CbType callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callbackType); + Assert(callback); + IConnection* connection = + new EvasMemberConnection1(callbackType, + callback, + callee, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + bool DisconnectCallback(IConnection* connection); + void DisconnectAll(); + + static void StaticOnDelEvent(void* data, + Evas* /*e*/, + Evas_Object* /*o*/, + void* /*ev*/); + + IConnectionsSet m_connections; + Evas_Object* m_object; + }; + + public: + EvasObject(); + explicit EvasObject(Evas_Object* object); + EvasObject(const EvasObject& other); + ~EvasObject(); + + EvasObject& operator=(const EvasObject& other); + EvasObject* operator=(Evas_Object* object); + + operator Evas_Object *(); + + bool IsValid() const + { + Assert(m_object); + return m_object->GetObject() != NULL; + } + + bool DisconnectCallback(IConnection* connection); + void DisconnectAll(); + + template + IConnection* ConnectSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartConnection::CbType + callback, + Args ... args) + { + Assert(m_object); + return m_object->ConnectSmartCallback(callbackName, callback, args ...); + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartMemberConnection2::CbType + callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberSmartCallback(callbackName, + callback, + callee, + arg1, + arg2); + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartMemberConnection1::CbType + callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberSmartCallback(callbackName, + callback, + callee, + arg1); + } + + template + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasConnection1::CbType + callback, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + return m_object->ConnectEvasCallback(callbackType, callback, arg1, arg2); + } + + template + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasConnection1::CbType + callback, + ArgType1* arg1) + { + Assert(m_object); + return m_object->ConnectEvasCallback(callbackType, callback, arg1); + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasMemberConnection1::CbType + callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberEvasCallback(callbackType, + callback, + callee, + arg1); + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasMemberConnection2::CbType + callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberEvasCallback(callbackType, + callback, + callee, + arg1, + arg2); + } + + private: + EvasObjectSharedPtr m_object; +}; +} +} //namespace +} //namespace + +#endif //WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H + diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup.h b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup.h new file mode 100644 index 0000000..149b7eb --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup inteface declaration + */ + +#ifndef WRT_SRC_POPUP_POPUP_H_ +#define WRT_SRC_POPUP_POPUP_H_ + +#include +#include +#include +#include +#include +#include "popup_object.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +struct AnswerCallbackData +{ + int buttonAnswer; + DPL::Optional password; + bool chackState; +}; + +class PopupManager; +class IPopup; +typedef std::shared_ptr IPopupPtr; + +class IPopup : public std::enable_shared_from_this +{ + public: + virtual void SetTitle(const std::string &title) = 0; + /*The object is deleted automatically after rendered */ + virtual void Append(PopupObject::IPopupObject *object) = 0; + + protected: + typedef void (*PopupCallbackType)(const AnswerCallbackData& answer, + void *data); + virtual void Show(PopupCallbackType callback, + void* data) = 0; + virtual ~IPopup() + {} + + private: + friend class PopupManager; + friend class std::shared_ptr; +}; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_H_ diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp new file mode 100644 index 0000000..b9bb5b3 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file popup_controller.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @bref Implementation file for popup controller + */ + +#include "popup_controller.h" +#include +#include +#include +#include + +IMPLEMENT_SINGLETON(Wrt::Popup::Renderer::PopupController) + +namespace Wrt { +namespace Popup { +namespace Renderer { +void CtrlPopup::SetTitle(const std::string &title) +{ + Assert(m_popup); + m_popup->SetTitle(title); +} + +void CtrlPopup::Append(PopupObject::IPopupObject *object) +{ + Assert(m_popup); + m_popup->Append(object); +} + +CtrlPopup::CtrlPopup(IPopupPtr popup) : + m_popup(popup), + m_callback() +{ + Assert(m_popup); +} + +CtrlPopup::~CtrlPopup() +{} + +void CtrlPopup::EmitAnswer(const AnswerCallbackData & answer) +{ + AnswerCallbackData l_answer = answer; + PopupAnswerEvent event(shared_from_this(), m_callback, l_answer); + DPL::Event::EventSupport::EmitEvent(event); +} + +PopupController::PopupController() : m_canvas(NULL) +{} + +CtrlPopupPtr PopupController::CreatePopup() const +{ + return CtrlPopupPtr( + new CtrlPopup(PopupManagerSingleton::Instance().CreatePopup())); +} + +void PopupController::OnEventReceived(const ShowPopupEventShort& event) +{ + CtrlPopupPtr popup = event.GetArg0(); + popup->m_callback = event.GetArg1(); + + //pass canvas from controller to manager + //canvas is not passed earlier because value wasn't set properly + PopupManagerSingleton::Instance().setExternalCanvas(getExternalCanvas()); + + PopupManagerSingleton::Instance().RunAsyncWithArgType( + popup->m_popup, + &PopupController::StaticOnAnswerReceived, + new CtrlPopupPtr(popup)); +} + +void PopupController::StaticOnAnswerReceived(const AnswerCallbackData & answer, + CtrlPopupPtr* popup) +{ + Assert(popup != NULL); + (*popup)->EmitAnswer(answer); + delete popup; // Just SharedPtr is destroyed, not the popup itself +} + +void PopupControllerUser::OnEventReceived(const PopupAnswerEvent& event) +{ + //Here we are in a proper context to call the callback + PopupAnswerCallback answerCall = event.GetArg1(); + AnswerCallbackData answer = event.GetArg2(); + answerCall.Call(answer); + event.GetArg0()->DPL::Event::EventSupport::RemoveListener( + this); +} + +void PopupControllerUser::ListenForAnswer(CtrlPopupPtr popup) +{ + popup->DPL::Event::EventSupport::AddListener(this); +} +} +} //namespace Popup +} //namespace Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.h b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.h new file mode 100644 index 0000000..066fd2d --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_controller.h @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file popup_controller.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @bref Header file for popup controller + */ + +/** + * To display a popup from a given class: + * + * class ABC + * { + * void AskUser() + * { + * } + * + * void DoSomeLogicWithAnswer() + * { + * } + * }; + * + * ... update the class to something simmilar: + * + * class ABC : Popup::PopupControllerUser + * { + * void AskUser() { + * using namespace Popup; + * CtrlPopupPtr popup = + * PopupControllerSingletion::Instance().CreatePopup(); + * popup->SetTitle("Title"); + * popup->SetContent("Content"); + * popup->AddButton("name1", 1); + * popup->AddButton("name2", 2); + * ListenForAnswer(popup); + * ShowPopupEvent event(popup, + * MakeAnswerCallback(this, + * &ABC::DoSomeLogicWithAnswer)); + * CONTROLLER_POST_EVENT(PopupController, event); + * } + * + * void DoSomeLogicWithAnswer(Popup::LabelId answer) { + * if (answer == 1) + * ;//name1 pressed + * else if (answer == 2) + * ;//name2 pressed + * } + * }; + **/ + +#ifndef WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ +#define WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "popup_manager.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +typedef int LabelId; + +struct PopupAnswerCallback +{ + typedef void (PopupAnswerCallback::*MemberPtr)(); + + void* callee; + MemberPtr member; + void (*callTranslator)(PopupAnswerCallback* callData, + const AnswerCallbackData& answer); + + void Call(const AnswerCallbackData& answer) + { + callTranslator(this, answer); + } +}; + +class PopupController; +class CtrlPopup; + +typedef std::shared_ptr CtrlPopupPtr; + +DECLARE_GENERIC_EVENT_3(PopupAnswerEvent, + CtrlPopupPtr, + PopupAnswerCallback, + AnswerCallbackData) + +DECLARE_GENERIC_EVENT_2(ShowPopupEventShort, + CtrlPopupPtr, + PopupAnswerCallback) + +class CtrlPopup : public DPL::Event::EventSupport, + public std::enable_shared_from_this +{ + public: + void SetTitle(const std::string &title); + void Append(PopupObject::IPopupObject *object); + + ~CtrlPopup(); + + private: + friend class PopupController; + friend class std::shared_ptr; + + explicit CtrlPopup(IPopupPtr popup); + void EmitAnswer(const AnswerCallbackData& answer); + + IPopupPtr m_popup; + PopupAnswerCallback m_callback; +}; + +class PopupController : + public DPL::Event::Controller::Type> +{ + public: + CtrlPopupPtr CreatePopup() const; + + void setExternalCanvas(void* canvas) + { + m_canvas = canvas; + } + void* getExternalCanvas() const + { + return m_canvas; + } + void* m_canvas; + + protected: + virtual void OnEventReceived(const ShowPopupEventShort& event); + PopupController(); + + private: + static void StaticOnAnswerReceived(const AnswerCallbackData& answer, + CtrlPopupPtr* popup); +}; + +class PopupControllerUser : DPL::Event::EventListener +{ + template + struct PopupAnswerCallbackCreator + { + typedef void (Type::*MemberPtr)(const AnswerCallbackData& answer); + union Caster + { + MemberPtr specific; + PopupAnswerCallback::MemberPtr generic; + }; + + static PopupAnswerCallback Create(Type* callee, + MemberPtr callback) + { + PopupAnswerCallback callData; + + callData.callee = callee; + + Caster caster; + caster.specific = callback; + callData.member = caster.generic; + + callData.callTranslator = + &PopupAnswerCallbackCreator::MemberCallbackTranslator; + + return callData; + } + + static void MemberCallbackTranslator(PopupAnswerCallback* callData, + const AnswerCallbackData& answer) + { + Type* typedThis = static_cast(callData->callee); + Caster caster; + caster.generic = callData->member; + MemberPtr typedCallback = caster.specific; + (typedThis->*typedCallback)(answer); + } + }; + + protected: + virtual void OnEventReceived(const PopupAnswerEvent& event); + void ListenForAnswer(CtrlPopupPtr popup); + + template + PopupAnswerCallback MakeAnswerCallback(Type* This, + void (Type::*callback) + (const AnswerCallbackData &)) + { + return PopupAnswerCallbackCreator::Create(This, callback); + } +}; + +typedef DPL::Singleton PopupControllerSingleton; +} +} //namespace Popup +} //namespace Wrt + +#endif //WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp new file mode 100644 index 0000000..040f445 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_manager.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup_manager implementation file + */ + +#include "popup_manager.h" +#include +#include +#include +#include +#include "popup.h" + +IMPLEMENT_SINGLETON(Wrt::Popup::Renderer::PopupManager) + +namespace Wrt { +namespace Popup { +namespace Renderer { +void PopupManager::Initialize(PopupRendererPtr renderer) +{ + Assert(!m_initialized); + m_popupRenderer = renderer; + m_popupRenderer->Initialize(); + m_initialized = true; +} + +void PopupManager::Deinitialize() +{ + m_popupRenderer->Deinitialize(); + Assert(m_initialized); + m_popupRenderer.reset(); + m_initialized = false; +} + +IPopupPtr PopupManager::CreatePopup() +{ + Assert(m_initialized); + return m_popupRenderer->CreatePopup(); +} +} +} // namespace Popup +} // namespace Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.h b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.h new file mode 100644 index 0000000..125ac22 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_manager.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_manager.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup_manager declaration file + */ + +#ifndef WRT_SRC_POPUP_POPUP_MANAGER_H_ +#define WRT_SRC_POPUP_POPUP_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include "popup.h" +#include "popup_renderer.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +class PopupManager : DPL::Noncopyable +{ + template + struct TemplatedPopupCallback + { + typedef void (*Type)(const AnswerCallbackData& answer, ArgType* data); + }; + + public: + PopupManager() : m_initialized(false) {} + ~PopupManager() + { + if (m_initialized) { + LogError("Destroyed without Deinitialize"); + } + } + void Initialize (PopupRendererPtr creator); + void Deinitialize(); + void SetPopupRenderer (PopupRendererPtr creator); + IPopupPtr CreatePopup(); + + template + void RunAsyncWithArgType( + IPopupPtr popup, + typename TemplatedPopupCallback::Type + callback, + ArgType* argument) + { + Assert(callback); + WrapCbAndArg* wrapped = + new WrapCbAndArg(callback, argument); + popup->Show(&CallbackArgTypeTranslator, wrapped); + } + + void Show(IPopupPtr popup, + IPopup::PopupCallbackType callback, + void* userdata) + { + popup->Show(callback, userdata); + } + + void setExternalCanvas(void* externalCanvas) + { + Assert(m_initialized && "Manger should be initialized"); + m_popupRenderer->setExternalCanvas(externalCanvas); + } + + private: + template + struct WrapCbAndArg + { + WrapCbAndArg(typename TemplatedPopupCallback::Type cb, + ArgType* arg) : + callback(cb), + argument(arg) + {} + + typename TemplatedPopupCallback::Type callback; + ArgType* argument; + }; + + template + static void CallbackArgTypeTranslator(const AnswerCallbackData & answer, + void* data) + { + WrapCbAndArg* wrapped = + static_cast< WrapCbAndArg* >(data); + wrapped->callback(answer, wrapped->argument); + delete wrapped; + } + + bool m_initialized; + PopupRendererPtr m_popupRenderer; +}; + +typedef DPL::Singleton PopupManagerSingleton; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_MANAGER_H_ diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_object.h b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_object.h new file mode 100644 index 0000000..86f7484 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_object.h @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_object.h + * @author Justyna Mejzner (j.mejzner@samsung.com) + * @version 1.0 + * @brief This is declaration file of PopupObject + */ + +#ifndef WRT_SRC_POPUP_POPUPOBJECT_H_ +#define WRT_SRC_POPUP_POPUPOBJECT_H_ + +#include + +#include +#include + +namespace Wrt { +namespace Popup { +namespace Renderer { +namespace PopupObject { +class IPopupObject; +class PopupObjectBase; +class Button; +class Label; +class Check; + +typedef std::list PopupObjects; + +enum PopupType +{ + BUTTON, + LABEL, + CHECK +}; + +class IPopupObject +{ + public: + virtual Button* asButton() = 0; + virtual Label* asLabel() = 0; + virtual Check* asCheck() = 0; + virtual PopupType getType() const = 0; + virtual ~IPopupObject() + {} +}; + +class PopupObjectBase : public IPopupObject +{ + public: + virtual Button* asButton() + { + Assert("wrong type"); + return NULL; + } + virtual Label* asLabel() + { + Assert("wrong type"); + return NULL; + } + virtual Check* asCheck() + { + Assert("wrong type"); + return NULL; + } + + PopupType getType() const + { + return m_type; + } + + protected: + PopupObjectBase(PopupType type) : m_type(type) + {} + + PopupType m_type; +}; + +class Button : public PopupObjectBase +{ + public: + Button(const std::string& label, + int labelId) : + PopupObjectBase(BUTTON), + m_label(label), + m_labelId(labelId) + {} + + Button* asButton() + { + return this; + } + + const std::string& getLabel() const + { + return m_label; + } + + int getLabelId() const + { + return m_labelId; + } + + private: + std::string m_label; + int m_labelId; +}; + +class Label : public PopupObjectBase +{ + public: + Label(const std::string &label) : + PopupObjectBase(LABEL), + m_label(label) + {} + + Label* asLabel() + { + return this; + } + + const std::string& getLabel() const + { + return m_label; + } + + private: + std::string m_label; +}; + +class Check : public PopupObjectBase +{ + public: + Check(const std::string &label) : + PopupObjectBase(CHECK), + m_checkLabel(label) + {} + + Check* asCheck() + { + return this; + } + + const std::string& getCheckLabel() const + { + return m_checkLabel; + } + + private: + std::string m_checkLabel; +}; +} /*PopupObject*/ +} +} //namespace Popup +} //namespace Wrt + +#endif //WRT_SRC_POPUP_POPUPOBJECT_H_ diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp new file mode 100644 index 0000000..0703bda --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp @@ -0,0 +1,421 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_renderer.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is efl specific implementation for PopupRenderer + */ + +#include "popup_renderer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "popup_manager.h" +#include "popup_manager.h" +#include "evas_object.h" + +namespace Wrt { +namespace { +using namespace Popup; +const char* EDJ_NAME = "/usr/share/edje/ace/generic_popup.edj"; +const char* POPUP_LAYOUT1 = "popup_layout1"; +const char* POPUP_LAYOUT2 = "popup_layout2"; +const char* POPUP_PART_TITLE = "title,text"; +const char* POPUP_PART_BUTTON1 = "button1"; +const char* POPUP_PART_BUTTON2 = "button2"; +const char* POPUP_PART_BUTTON3 = "button3"; +const char* BUTTON_CLICKED_CALLBACK_NAME = "clicked"; +const char* CHANGED_CALLBACK_NAME = "changed"; +const unsigned int MAX_NUMBER_OF_VERTICAL = 2; + +Evas_Object* create_layout_main(Evas_Object* parent, int totalV) +{ + Evas_Object *layout = elm_layout_add(parent); + + if (totalV == 1) { + elm_layout_file_set(layout, EDJ_NAME, POPUP_LAYOUT1); + } else if (totalV == 2) { + elm_layout_file_set(layout, EDJ_NAME, POPUP_LAYOUT2); + } else { + Assert("popup needs define new group in the edc"); + } + + evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + return layout; +} +} //namespace + +namespace Popup { +namespace Renderer { +class PopupRenderer::Impl +{ + public: + Impl() : + m_popupsToRender(), + m_current(), + m_initialized(false), + m_checkState(false), + m_themeIndexV(0), + m_externalCanvas(NULL) + {} + + ~Impl() + { + if (m_initialized) { + LogError("Destroyed without Deinitialize"); + } + } + + void Initialize() + { + Assert(!m_initialized); + m_initialized = true; + } + + void Deinitialize() + { + Assert(m_initialized); + m_current.reset(); + while (!m_popupsToRender.empty()) { + m_popupsToRender.pop(); + } + m_initialized = false; + } + + void ButtonCallback(EvasObject::IConnection* /*connection*/, + void* /*event_info*/, + void* data) + { + LogDebug("ButtonCallback"); + Assert(m_initialized); + AnswerCallbackData answerData; + + answerData.buttonAnswer = reinterpret_cast(data); + answerData.chackState = m_checkState; + answerData.password = m_password; + m_current->ForwardAnswer(answerData); + m_current.reset(); + + FOREACH(it, m_createdObjects) + { + if (it->IsValid()) { + evas_object_del(*it); + } + } + m_createdObjects.clear(); + m_checkState = false; + DoRender(); + } + + void CheckCallback(EvasObject::IConnection* connection, + void* /*event_info*/, + void* /* unused */) + { + m_checkState = + elm_check_state_get(connection->GetEvasObject()); + } + + void Render (PopupPtr popup) + { + Assert(m_initialized); + m_popupsToRender.push(popup); + DoRender(); + } + + void DoRender(const PopupObject::Label& object, + EvasObject& parent, + EvasObject& layout, + int themeIndex) + { + EvasObject label(elm_label_add(parent)); + + elm_object_style_set(label, "popup_description/default"); + elm_label_line_wrap_set(label, ELM_WRAP_WORD); + elm_object_text_set(label, object.getLabel().c_str()); + evas_object_size_hint_weight_set(label, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(label, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(label); + + elm_object_part_content_set( + layout, + DPL::lexical_cast(themeIndex).c_str(), + label); + m_createdObjects.push_back(label); + } + + void DoRender(const PopupObject::Check& object, + EvasObject& parent, + EvasObject& layout, + int themeIndex) + { + EvasObject check(elm_check_add(parent)); + + evas_object_size_hint_align_set(check, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_size_hint_weight_set(check, EVAS_HINT_EXPAND, 0.0); + elm_object_text_set(check, + object.getCheckLabel().c_str()); + elm_object_part_content_set( + layout, + DPL::lexical_cast(themeIndex).c_str(), + check); + + check.ConnectMemberSmartCallback(CHANGED_CALLBACK_NAME, + &Impl::CheckCallback, + this, + static_cast(NULL)); + evas_object_show(check); + m_createdObjects.push_back(check); + } + + void DoRender(const PopupObject::Button& object, + EvasObject &parent) + { + EvasObject btn(elm_button_add(parent)); + + elm_object_text_set(btn, object.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON1, btn); + btn.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast(object. + getLabelId())); + m_createdObjects.push_back(btn); + } + + void DoRender(const PopupObject::Button& object1, + const PopupObject::Button& object2, + EvasObject &parent) + { + DoRender(object1, parent); + + EvasObject btn2(elm_button_add(parent)); + + elm_object_text_set(btn2, object2.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON2, btn2); + btn2.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast(object2. + getLabelId())); + m_createdObjects.push_back(btn2); + } + + void DoRender(const PopupObject::Button& object1, + const PopupObject::Button& object2, + const PopupObject::Button& object3, + EvasObject &parent) + { + DoRender(object1, object2, parent); + + EvasObject btn3(elm_button_add(parent)); + + elm_object_text_set(btn3, object3.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON3, btn3); + btn3.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast(object3. + getLabelId())); + m_createdObjects.push_back(btn3); + } + + EvasObject getBaseObject() + { + if (getExternalCanvas() == NULL) { + LogDebug("Create old style popup"); + EvasObject win(elm_win_add(NULL, "Popup", ELM_WIN_DIALOG_BASIC)); + elm_win_borderless_set(win, EINA_TRUE); + elm_win_alpha_set(win, EINA_TRUE); + elm_win_raise(win); + { + int w, h, x, y; + ecore_x_window_geometry_get(ecore_x_window_root_first_get(), + &x, + &y, + &w, + &h); + evas_object_resize(win, w, h); + evas_object_move(win, x, y); + } + m_createdObjects.push_back(win); + evas_object_show(win); + return win; + } else { + LogDebug("Create new style popup"); + EvasObject win(getExternalCanvas()); + evas_object_show(win); + return win; + } + } + + void DoRender() + { + if (!m_current && !m_popupsToRender.empty()) { + m_current = m_popupsToRender.front(); + m_popupsToRender.pop(); + + m_themeIndexV = 0; + + // preprocessing + std::vector countPopupObjects = { 0 /* PopupObject::BUTTON */, + 0 /* PopupObject::LABEL */, + 0 /* PopupObject::CHECK */ }; + FOREACH(it, m_current->GetPopupObjects()) { + Assert((*it)->getType() < countPopupObjects.size() && + "Wrong PopupObject assigned"); + countPopupObjects[(*it)->getType()]++; + } + int needsIndexV = countPopupObjects[PopupObject::LABEL] + + countPopupObjects[PopupObject::CHECK]; + + EvasObject win = getBaseObject(); + EvasObject main(elm_popup_add(win)); + + evas_object_size_hint_weight_set(main, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + elm_object_part_text_set(main, + POPUP_PART_TITLE, + m_current->GetTitle().c_str()); + + m_createdObjects.push_back(main); + std::vector buttonObjectList; + EvasObject layout(create_layout_main(main, needsIndexV)); + m_createdObjects.push_back(layout); + + FOREACH(it, m_current->GetPopupObjects()) { + switch ((*it)->getType()) { + case PopupObject::BUTTON: + buttonObjectList.push_back(*(*it)->asButton()); + break; + case PopupObject::LABEL: + DoRender(*(*it)->asLabel(), + main, + layout, + m_themeIndexV++); + break; + case PopupObject::CHECK: + DoRender(*(*it)->asCheck(), + main, + layout, + m_themeIndexV++); + break; + default: + Assert("incorrect type"); + } + Assert(m_themeIndexV <= MAX_NUMBER_OF_VERTICAL); + } + elm_object_content_set(main, + layout); + + // show buution + switch (buttonObjectList.size()) { + case 0: + LogDebug("no button"); + break; + case 1: + DoRender(buttonObjectList.at(0), + main); + break; + case 2: + DoRender(buttonObjectList.at(0), + buttonObjectList.at(1), + main); + break; + case 3: + DoRender(buttonObjectList.at(0), + buttonObjectList.at(1), + buttonObjectList.at(2), + main); + break; + default: + Assert("incorrect button number"); + break; + } + + evas_object_show(main); + } + } + + void setExternalCanvas(void* externalCanvas) + { + m_externalCanvas = static_cast(externalCanvas); + } + + Evas_Object* getExternalCanvas() const + { + return m_externalCanvas; + } + + std::queue m_popupsToRender; + std::list m_createdObjects; + PopupPtr m_current; + bool m_initialized; + bool m_checkState; + DPL::Optional m_password; + unsigned int m_themeIndexV; + + private: + Evas_Object* m_externalCanvas; +}; + +PopupRenderer::PopupRenderer() +{ + m_impl = new PopupRenderer::Impl(); +} + +PopupRenderer::~PopupRenderer() +{ + delete m_impl; +} + +void PopupRenderer::Initialize() +{ + Assert(m_impl); + m_impl->Initialize(); +} + +void PopupRenderer::Deinitialize() +{ + Assert(m_impl); + m_impl->Deinitialize(); +} + +IPopupPtr PopupRenderer::CreatePopup() +{ + return std::static_pointer_cast(IPopupPtr + (new Popup(shared_from_this()))); +} + +void PopupRenderer::Render(PopupPtr popup) +{ + m_impl->Render(popup); +} + +void PopupRenderer::setExternalCanvas(void* externalCanvas) +{ + m_impl->setExternalCanvas(externalCanvas); +} +} +} // namespace Popup +} // namespace Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h new file mode 100644 index 0000000..3538bbb --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_renderer.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is declaration file of PopupRenderer + */ + +#ifndef WRT_SRC_POPUP_POPUP_RENDERER_H_ +#define WRT_SRC_POPUP_POPUP_RENDERER_H_ + +#include +#include +#include + +#include +#include +#include +#include +#include "popup.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +class PopupRenderer : public std::enable_shared_from_this +{ + public: + PopupRenderer(); + ~PopupRenderer(); + void Initialize(); + void Deinitialize(); + IPopupPtr CreatePopup(); + virtual void setExternalCanvas(void* externalCanvas); + + protected: + class Popup; + typedef std::shared_ptr PopupPtr; + + class Popup : public IPopup + { + public: + typedef std::map ButtonMap; + virtual void SetTitle(const std::string &title) + { + LogDebug(title); + Assert(m_title.empty()); + m_title = title; + } + + virtual void Append(PopupObject::IPopupObject *object) + { + m_popupObjectList.push_back(object); + } + + virtual void Show(IPopup::PopupCallbackType callback, + void* data) + { + Assert(callback); + m_data = data; + m_callback = callback; + m_renderer->Render(std::static_pointer_cast(shared_from_this())); + } + + const std::string& GetTitle() const + { + return m_title; + } + + PopupObject::PopupObjects& GetPopupObjects() + { + return m_popupObjectList; + } + + virtual ~Popup() + { + FOREACH(it, m_popupObjectList) { + delete *it; + } + } + + private: + friend class PopupRenderer; + friend class std::shared_ptr; + friend class PopupObjectTheme; + + Popup(std::shared_ptr renderer) : m_renderer(renderer) + {} + + void ForwardAnswer(const AnswerCallbackData & answer) const + { + m_callback(answer, m_data); + } + + std::string m_title; + void* m_data; + IPopup::PopupCallbackType m_callback; + PopupObject::PopupObjects m_popupObjectList; + std::shared_ptr m_renderer; + }; + + private: + void Render (PopupPtr popup); + + class Impl; + Impl* m_impl; +}; + +typedef std::shared_ptr PopupRendererPtr; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_RENDERER_H_ diff --git a/src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.cpp b/src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.cpp new file mode 100644 index 0000000..41d683d --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "wrt-popup.h" +#include +#include + +#include +#include +#include +#include + +#include "PopupEnum.h" +#include "PopupSerializer.h" +#include "YesNoPopup.h" +#include "InfoPopup.h" +#include "YesNoCheckPopup.h" + +namespace Wrt { +namespace Popup { +bool WrtPopup::openPipes() +{ + Try + { + if (m_argc != 3) { + LogError("Wrong arguments!"); + return false; + } + m_input.Open(m_argv[1]); + //open output pipe + m_output.Open(m_argv[2]); + + DPL::WaitableHandleWatchSupport::InheritedContext()-> + AddWaitableHandleWatch(this, + m_input.WaitableReadHandle(), + DPL::WaitMode::Read); + m_pipesOpened = true; + return true; + } + Catch(DPL::Exception) + { + LogError("cannot open pipes"); + } + return false; +} + +void WrtPopup::closePipes() +{ + Try + { + if (m_pipesOpened) { + DPL::WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, + m_input.WaitableReadHandle(), + DPL::WaitMode::Read); + m_input.Close(); + m_output.Close(); + m_pipesOpened = false; + } + } + Catch(DPL::Exception) + { + LogError("cannot close pipes"); + } +} + +void WrtPopup::OnEventReceived(const QuitEvent & /* event */) +{ + LogDebug("Quiting"); + closePipes(); + Quit(); +} + +void WrtPopup::OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type /*mode*/) +{ + if (waitableHandle == m_input.WaitableReadHandle()) { + readInputData(); + } +} + +void WrtPopup::readInputData() +{ + DPL::BinaryQueueAutoPtr data = + m_input.Read(std::numeric_limits::max()); + int popupType = PopupSerializer::getIntArg(*data); + LogDebug("popup type " << popupType); + switch (popupType) { + case YES_NO_PROMPT: + m_popup.reset(new YesNoPopup()); + m_popup->show(data, this); + break; + case INFO_PROMPT: + m_popup.reset(new InfoPopup()); + m_popup->show(data, this); + break; + case YES_NO_CHECK_PROMPT: + m_popup.reset(new YesNoCheckPopup()); + m_popup->show(data, this); + break; + default: + Assert(false); + } +} + +void WrtPopup::response(DPL::BinaryQueue result) +{ + m_output.Write(result, result.Size()); + PostEvent(QuitEvent()); +} + +void WrtPopup::OnStop() +{ + LogDebug("On Stop"); +} + +void WrtPopup::OnCreate() +{ + if (!openPipes()) { + PostEvent(QuitEvent()); + } + LogDebug("On Create"); +} + +void WrtPopup::OnResume() +{ + LogDebug("OnResume"); +} + +void WrtPopup::OnPause() +{ + LogDebug("OnPause"); +} + +void WrtPopup::OnReset(bundle */*b*/) +{ + LogDebug("OnReset"); +} + +void WrtPopup::OnTerminate() +{ + LogDebug("Wrt Shutdown now"); +} + +WrtPopup::WrtPopup(int argc, char **argv) : + Application(argc, argv, "wrt-popup", false), + m_pipesOpened(false) +{ + Touch(); + Renderer::PopupControllerSingleton::Instance().Touch(); + Renderer::PopupManagerSingleton::Instance().Initialize( + Renderer::PopupRendererPtr(new Renderer::PopupRenderer)); + LogDebug("App Created"); +} + +WrtPopup::~WrtPopup() +{ + Renderer::PopupManagerSingleton::Instance().Deinitialize(); + LogDebug("App Finished"); +} +} +} + +int main(int argc, char *argv[]) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // Output on stdout will be flushed after every newline character, + // even if it is redirected to a pipe. This is useful for running + // from a script and parsing output. + // (Standard behavior of stdlib is to use full buffering when + // redirected to a pipe, which means even after an end of line + // the output may not be flushed). + setlinebuf(stdout); + + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT-POPUP"); + Wrt::Popup::WrtPopup app(argc, argv); + int ret = app.Exec(); + LogDebug("App returned: " << ret); + return ret; + } + UNHANDLED_EXCEPTION_HANDLER_END +} diff --git a/src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.h b/src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.h new file mode 100644 index 0000000..ab9c519 --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-bin/wrt-popup.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_H +#define WRT_POPUP_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "popup_controller.h" + +namespace Wrt { +namespace Popup { +DECLARE_GENERIC_EVENT_0(QuitEvent) +class WrtPopup; + +class IPopup : public Renderer::PopupControllerUser +{ + public: + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) = 0; + virtual ~IPopup() {} +}; + +typedef std::unique_ptr IPopupPtr; + +class WrtPopup : + public DPL::WaitableHandleWatchSupport::WaitableHandleListener, + public DPL::Application, + private DPL::Event::Controller::Type> +{ + public: + WrtPopup(int argc, char **argv); + virtual ~WrtPopup(); + + void response(DPL::BinaryQueue result); + + protected: + //DPL::Application functions + virtual void OnStop(); + virtual void OnCreate(); + virtual void OnResume(); + virtual void OnPause(); + virtual void OnReset(bundle *b); + virtual void OnTerminate(); + virtual void OnEventReceived(const QuitEvent &event); + virtual void OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type mode); + + private: + + void showAcePrompt(DPL::BinaryQueueAutoPtr data); + void communicationBoxResponse(int buttonAnswer, + bool checkState, + void* userdata); + bool m_pipesOpened; + IPopupPtr m_popup; + + bool openPipes(); + void closePipes(); + void readInputData(); + + DPL::NamedInputPipe m_input; + DPL::NamedOutputPipe m_output; +}; +} +} + +#endif // WRT_POPUP_H diff --git a/src_mobile/wrt-popup/wrt/popup-runner/CMakeLists.txt b/src_mobile/wrt-popup/wrt/popup-runner/CMakeLists.txt new file mode 100644 index 0000000..0a8f45e --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-runner/CMakeLists.txt @@ -0,0 +1,66 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_RUNNER_LIB_DEP + dpl-efl + REQUIRED +) + +set(WRT_POPUP_RUNNER_LIB_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/wrt/popup-runner) + +set(WRT_POPUP_RUNNER_LIB_SOURCES + ${WRT_POPUP_COMMON_SRCS} + ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/PopupInvoker.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_RUNNER_LIB_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_RUNNER_LIB_SRC_DIR} + ${WRT_POPUP_RUNNER_LIB_DEP_INCLUDE_DIRS} + ${WRT_POPUP_COMMON_DIR} +) + +ADD_LIBRARY(${TARGET_POPUP_WRT_RUNNER_LIB} SHARED + ${WRT_POPUP_RUNNER_LIB_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_POPUP_WRT_RUNNER_LIB} + ${WRT_POPUP_RUNNER_LIB_DEP_LIBRARIES} + ${WRT_POPUP_RUNNER_LIB_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_WRT_RUNNER_LIB} + DESTINATION lib +) + +INSTALL(FILES ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/PopupInvoker.h + DESTINATION ${DESTINATION_HEADERS_WRT_POPUP_RUNNER} +) diff --git a/src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.cpp b/src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.cpp new file mode 100644 index 0000000..16cbace --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "PopupInvoker.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "PopupEnum.h" +#include "PopupSerializer.h" + +namespace { +const char *POPUP_EXEC = "/usr/bin/wrt-popup-wrt-runtime"; +} + +namespace Wrt { +namespace Popup { +PopupInvoker::PopupInvoker() +{ + char tmp[L_tmpnam + 1]; + if (NULL == tmpnam(tmp)) + ThrowMsg(DPL::Exception, "Failed to get pipe name"); + m_inputName = tmp; + + if (NULL == tmpnam(tmp)) + ThrowMsg(DPL::Exception, "Failed to get pipe name"); + m_outputName = tmp; + + m_input.Create(m_inputName); + m_output.Create(m_outputName); + LogDebug("Pipes created"); +} + +PopupInvoker::~PopupInvoker() +{ + Try + { + m_input.Destroy(m_inputName); + m_output.Destroy(m_outputName); + LogDebug("Pipes destroyed"); + } + Catch(DPL::Exception) + { + LogError("Cannot destroy pipes"); + } +} + +bool PopupInvoker::askYesNo(const std::string& title, + const std::string& message) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(YES_NO_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + + //Result from popup application is available. Read it. + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits::max()); + const int success = PopupSerializer::getIntArg(*resultData); + bool retVal = false; + if (success) { + const int result = PopupSerializer::getIntArg(*resultData); + + LogDebug("Popup result is: " << result); + + Assert(resultData->Empty()); + retVal = (!!result); + } else { + LogWarning("Failed to show popup."); + } + + tmp.Close(); + m_input.Close(); + m_output.Close(); + + return retVal; + } + Catch(DPL::Exception) + { + LogError("error occured"); + } + + return false; +} + +void PopupInvoker::showInfo(const std::string& title, + const std::string& message, + const std::string& buttonLabel) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(INFO_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + PopupSerializer::appendArg(buttonLabel, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits::max()); + const int success = PopupSerializer::getIntArg(*resultData); + if (!success) { + LogWarning("Failed to show popup."); + } + //ignore result + + tmp.Close(); + m_input.Close(); + m_output.Close(); + } + Catch(DPL::Exception) + { + LogError("error occured"); + } +} + +PopupResponse PopupInvoker::askYesNoCheckbox(const std::string& title, + const std::string& message, + const std::string& checkboxLabel) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(YES_NO_CHECK_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + PopupSerializer::appendArg(checkboxLabel, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + + //Result from popup application is available. Read it. + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits::max()); + const int success = PopupSerializer::getIntArg(*resultData); + if (success) { + const int result = PopupSerializer::getIntArg(*resultData); + const int rememberResult = PopupSerializer::getIntArg(*resultData); + + LogDebug( + "Popup result is: " << result << " remeber: " << rememberResult); + + Assert(resultData->Empty()); + tmp.Close(); + m_input.Close(); + m_output.Close(); + + if (1 == result) { + if (rememberResult == 1) { + return YES_DO_REMEMBER; + } else { + return YES_DONT_REMEMBER; + } + } else { + if (rememberResult == 1) { + return NO_DO_REMEMBER; + } else { + return NO_DONT_REMEMBER; + } + } + } else { + LogWarning("Popup failed to execute."); + tmp.Close(); + m_input.Close(); + m_output.Close(); + return NO_DONT_REMEMBER; + } + } + Catch(DPL::Exception) + { + LogError("error occured"); + } + return NO_DONT_REMEMBER; +} + +void PopupInvoker::executePopup() +{ + pid_t pid = fork(); + if (pid == -1) { + //error occured + LogError("Failed to create popup process."); + Assert(false); + } + if (pid == 0) { + //child process + int ret = execl(POPUP_EXEC, + POPUP_EXEC, + m_outputName.c_str(), + m_inputName.c_str(), + NULL); + if (ret == -1) { + //execl returns -1 on error + LogError("Failed to set popup binary"); + //write something to pipe to unblock caller process + DPL::NamedOutputPipe errOut; + errOut.Open(m_inputName); + DPL::BinaryQueue data; + PopupSerializer::appendArg(false, data); + errOut.Write(data, data.Size()); + errOut.Close(); + + Assert(false); + } + } + + DPL::WaitableHandle handle = m_input.WaitableReadHandle(); + DPL::WaitForSingleHandle(handle); +} +} // Popup +} // Wrt diff --git a/src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.h b/src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.h new file mode 100644 index 0000000..278db6d --- /dev/null +++ b/src_mobile/wrt-popup/wrt/popup-runner/PopupInvoker.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_INVOKER_H +#define WRT_POPUP_INVOKER_H + +#include + +#include +#include + +/* + * + * Example usage: + * + * bool result = PopupInvoker().askYesNo("title", "message"); + * + */ + +namespace Wrt { +namespace Popup { +enum PopupResponse { + NO_DO_REMEMBER, + NO_DONT_REMEMBER, + YES_DONT_REMEMBER, + YES_DO_REMEMBER +}; + +class PopupInvoker +{ + public: + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, PopupInvokerException) + }; + + PopupInvoker(); + ~PopupInvoker(); + + bool askYesNo(const std::string &title, const std::string &message); + void showInfo(const std::string &title, + const std::string &message, + const std::string &buttonLabel = std::string("OK")); + PopupResponse askYesNoCheckbox(const std::string& title, + const std::string& message, + const std::string& checkboxLabel); + + private: + + void executePopup(); + + DPL::NamedInputPipe m_input; + DPL::NamedOutputPipe m_output; + std::string m_inputName; + std::string m_outputName; +}; +} // Popup +} // Wrt + +#endif diff --git a/src_wearable/CMakeLists.txt b/src_wearable/CMakeLists.txt new file mode 100644 index 0000000..ba7daa0 --- /dev/null +++ b/src_wearable/CMakeLists.txt @@ -0,0 +1,67 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Includes CMake configuration file (*.cmake), preserving appropriate paths. + +ADD_DEFINITIONS("-DWRT_PLUGINS_COMMON_LOG") + +macro(include_config_file INCLUDED_CONFIG_FILE_PATH) + get_filename_component(CURRENT_CONFIG_FILE_PATH ${CMAKE_CURRENT_LIST_FILE} PATH) + include(${CURRENT_CONFIG_FILE_PATH}/${INCLUDED_CONFIG_FILE_PATH}/${CONFIG_FILE_NAME} OPTIONAL) +endmacro() + +# Gets actual path for CMake configuration file (*.cmake). +# By default, if no argument is passed, current path will be set to variable +# named CURRENT_PATH. +# @param [Optional] Name of the variable to set with current path. +macro(get_current_path) + set(VARIABLE "CURRENT_PATH") + if (${ARGC} GREATER 0) + set(VARIABLE ${ARGV0}) + endif () + get_filename_component(${VARIABLE} ${CMAKE_CURRENT_LIST_FILE} PATH) +endmacro() + +set(HOST_ARCH $ENV{DEB_HOST_ARCH}) +if("${HOST_ARCH}" MATCHES "armel") + set(HOST_ARCH "armel") +endif() + +#target names +set(TARGET_PLUGIN_LOADING_LIB "wrt-plugin-loading") +set(TARGET_COMMONS "wrt-plugins-commons") +set(TARGET_COMMONS_JAVASCRIPT "wrt-plugins-commons-javascript") +set(TARGET_JS_OVERLAY "wrt-plugins-js-overlay") +SET(TARGET_POPUP_ACE "wrt-popup-ace-runtime") +SET(TARGET_POPUP_ACE_RUNNER_LIB "wrt-popup-ace-runner") +SET(TARGET_POPUP_WRT "wrt-popup-wrt-runtime") +SET(TARGET_POPUP_WRT_RUNNER_LIB "wrt-popup-wrt-runner") +set(TARGET_PLUGINS_API_SUPPORT "wrt-plugins-api-support") +set(TARGET_PLUGINS_IPC_MESSAGE_LIB "wrt-plugins-ipc-message") + +set(PLUGIN_LOADING_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugin-loading) +set(PLUGINS_API_SUPPORT_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins-api-support) +set(PLUGINS_IPC_MESSAGE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins-ipc-message) + +add_subdirectory(plugins-api-support) +add_subdirectory(plugin-loading) +add_subdirectory(js-overlay) +add_subdirectory(Commons) +add_subdirectory(CommonsJavaScript) +add_subdirectory(dispatch-event) +add_subdirectory(modules) +add_subdirectory(standards) +add_subdirectory(wrt-popup) +add_subdirectory(plugins-installer) +add_subdirectory(plugins-ipc-message) diff --git a/src_wearable/Commons/Base64.cpp b/src_wearable/Commons/Base64.cpp new file mode 100644 index 0000000..94ac901 --- /dev/null +++ b/src_wearable/Commons/Base64.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Copyright (c) 2003-2007, Bicom Systems Ltd. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of the Bicom Systems Ltd nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * Denis Komadaric, + * Bicom Systems Ltd. + */ +#include +#include "Exception.h" +#include "Base64.h" + +namespace WrtDeviceApis { +namespace Commons { +const std::string Base64::chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +bool Base64::is_base64(unsigned char c) +{ + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string Base64::encode(unsigned char* data, + std::size_t num) +{ + std::string ret; + int i = 0; + int j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (num--) { + char_array_3[i++] = *(data++); + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & + 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & + 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; i < 4; ++i) { + ret += chars[char_array_4[i]]; + } + i = 0; + } + } + + if (i != 0) { + for (j = i; j < 3; ++j) { + char_array_3[j] = '\0'; + } + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (j = 0; (j < i + 1); ++j) { + ret += chars[char_array_4[j]]; + } + + while ((i++ < 3)) { + ret += '='; + } + } + + return ret; +} + +std::string Base64::decode(const std::string& str) +{ + if (!is_base64_string(str)) { + ThrowMsg(InvalidArgumentException, + "Invalid length of base64 string."); + } + int in_len = str.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && (str[in_] != '=')) { + if (!is_base64(str[in_])) { + ThrowMsg(InvalidArgumentException, + "Invalid characters in base64 string."); + } + char_array_4[i++] = str[in_]; + in_++; + if (i == 4) { + for (i = 0; i < 4; ++i) { + char_array_4[i] = chars.find(char_array_4[i]); + } + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & + 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; i < 3; ++i) { + ret += char_array_3[i]; + } + i = 0; + } + } + + if (i != 0) { + for (j = i; j < 4; ++j) { + char_array_4[j] = 0; + } + + for (j = 0; j < 4; ++j) { + char_array_4[j] = chars.find(char_array_4[j]); + } + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (j = 0; (j < i - 1); ++j) { + ret += char_array_3[j]; + } + } + + return ret; +} + +bool Base64::is_base64_string(const std::string& str) +{ + return ((str.size() % 4) == 0); +} +} +} //WrtDeviceApisCommon diff --git a/src_wearable/Commons/Base64.h b/src_wearable/Commons/Base64.h new file mode 100644 index 0000000..5f42802 --- /dev/null +++ b/src_wearable/Commons/Base64.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_BASE64_H_ +#define WRTDEVICEAPIS_COMMONS_BASE64_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class Base64 +{ + public: + static std::string encode(unsigned char* data, + std::size_t num); + static std::string decode(const std::string& str); + + private: + static bool is_base64(unsigned char c); + static bool is_base64_string(const std::string& str); + + private: + static const std::string chars; +}; // Base64 +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_BASE64_H_ */ diff --git a/src_wearable/Commons/CMakeLists.txt b/src_wearable/Commons/CMakeLists.txt new file mode 100644 index 0000000..6b58193 --- /dev/null +++ b/src_wearable/Commons/CMakeLists.txt @@ -0,0 +1,106 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}) +endmacro() + +macro(install_wrtaccess_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}/WrtAccess) +endmacro() + +macro(install_widget_interface_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}/WidgetInterface) +endmacro() + +include_config_file(WrtAccess) + +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) +pkg_search_module(ace-client REQUIRED security-client) +pkg_search_module(dpl-event REQUIRED dpl-event-efl) +pkg_search_module(icu REQUIRED icu-i18n) + +set(WRT_COMMONS_DEPENDECIES_INCLUDES + ${wrt-plugin-api_INCLUDE_DIRS} + ${ace-client_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} + ${icu_INCLUDE_DIRS} + ) + +include_directories(${WRT_COMMONS_DEPENDECIES_INCLUDES}) + +set(TARGET_NAME ${TARGET_COMMONS}) + +set(SRCS + ${SRCS_WRT_ACCESS} + ${CMAKE_CURRENT_SOURCE_DIR}/Base64.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/FunctionDefinition.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Regex.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/RegexUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/StringBuilder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/StringUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ThreadPool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSObjectDeclaration.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSObject.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/TimeUtils.cpp + #PARENT_SCOPE +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${ace-client_LIBRARIES} + ${dpl-event_LIBRARIES} + ${icu_LIBRARIES} + ${TARGET_POPUP_ACE_RUNNER_LIB} +) + +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}) + +install_header_file(FunctionDeclaration.h) +install_header_file(FunctionDefinition.h) +install_header_file(Base64.h) +install_header_file(Deprecated.h) +install_header_file(Dimension.h) +install_header_file(Emitters.h) +install_header_file(EventListener.h) +install_header_file(EventReceiver.h) +install_header_file(Exception.h) +install_header_file(IEvent.h) +install_header_file(IExternEventCanceler.h) +install_header_file(ListenerEventEmitter.h) +install_header_file(ListenerEvent.h) +install_header_file(Range.h) +install_header_file(Regex.h) +install_header_file(RegexPatterns.h) +install_header_file(RegexUtils.h) +install_header_file(StaticAssert.h) +install_header_file(StringBuilder.h) +install_header_file(StringUtils.h) +install_header_file(ThreadPool.h) +install_header_file(TypesDeclaration.h) +install_header_file(TypeTraits.h) +install_header_file(plugin_initializer_def.h) +install_header_file(JSObjectDeclaration.h) +install_header_file(JSObject.h) +install_header_file(TimeUtils.h) +install_wrtaccess_header_file(WrtAccess/WrtAccess.h) diff --git a/src_wearable/Commons/DESCRIPTION b/src_wearable/Commons/DESCRIPTION new file mode 100644 index 0000000..7f04546 --- /dev/null +++ b/src_wearable/Commons/DESCRIPTION @@ -0,0 +1 @@ +Common code diff --git a/src_wearable/Commons/Deprecated.h b/src_wearable/Commons/Deprecated.h new file mode 100644 index 0000000..5db3acf --- /dev/null +++ b/src_wearable/Commons/Deprecated.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_DEPRECATED_H_ +#define WRTDEVICEAPIS_COMMONS_DEPRECATED_H_ + +#define WRT_PLUGINS_DEPRECATED __attribute__((deprecated)) + +#endif /* WRTDEVICEAPIS_COMMONS_DEPRECATED_H_ */ diff --git a/src_wearable/Commons/Dimension.h b/src_wearable/Commons/Dimension.h new file mode 100644 index 0000000..703e0c0 --- /dev/null +++ b/src_wearable/Commons/Dimension.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_DIMENSION_H_ +#define WRTDEVICEAPIS_COMMONS_DIMENSION_H_ + +namespace WrtDeviceApis { +namespace Commons { +/** + * Encapsulates width and height of a component. + */ +class Dimension +{ + public: + /** + * Type of dimension's values. + */ + typedef unsigned int ValueType; + + public: + /** + * Creates an instance of Dimension with specified width and height. + * @param width Specified width. + * @param height Specified height. + */ + Dimension(ValueType width, + ValueType height) : + m_width(width), + m_height(height) + {} + + ValueType getWidth() const + { + return m_width; + } + + ValueType getHeight() const + { + return m_height; + } + + void setSize(ValueType width, + ValueType height) + { + m_width = width; + m_height = height; + } + + private: + ValueType m_width; + ValueType m_height; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_DIMENSION_H_ diff --git a/src_wearable/Commons/Emitters.h b/src_wearable/Commons/Emitters.h new file mode 100644 index 0000000..7b1d8c2 --- /dev/null +++ b/src_wearable/Commons/Emitters.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_EMITTERS_H_ +#define WRTDEVICEAPIS_COMMONS_EMITTERS_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Manages listener events emitters. + * Template parameter should be class that derives from @see ListenerEvent. + */ +template +class Emitters +{ + public: + typedef EmitterClass EmitterType; + typedef DPL::SharedPtr EmitterPtrType; + typedef typename EmitterType::IdType EmitterIdType; + typedef typename EmitterType::EventType EventType; + typedef typename EmitterType::EventPtrType EventPtrType; + typedef std::auto_ptr LockType; + + public: + ~Emitters() + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_emitters.clear(); + } + + /** + * Attaches emitter. + * @param emitter Emitter. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + void attach(const EmitterPtrType& emitter) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_emitters[emitter->getId()] = emitter; + } + + /** + * Detaches emitter. + * @param id Id of an emitter. + * @return True when emitter was found and successfully detached, + * false otherwise. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + bool detach(const EmitterIdType id) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + return (m_emitters.erase(id) > 0); + } + + /** + * Emits event through all emitters. + * @param event Event to emit. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + void emit(const EventPtrType& event) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + for (Iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { + it->second->emit(event); + } + } + + /** + * Emits event through those emitters that when passed to predicate result + * in + * returning true by it. + * @param event Event to emit. + * @param pred Predicate - a callable object (function, functor) that takes + * an argument of type EmitterPtrType and returns boolean value. + */ + template + void emitIf(const EventPtrType& event, + Predicate pred) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + for (Iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { + if (bool(pred(it->second))) { + it->second->emit(event); + } + } + } + + /** + * Checks whether emitter of supplied id is attached. + * @param emitter Emitter. + * @return True when emitter has been found, false otherwise. + * @remarks Can be used within scope of getLock() call. + */ + bool isAttached(const EmitterIdType id) const + { + return (m_emitters.count(id) > 0); + } + + /** + * Returns number of attached emitters. + * @return Number of emitters. + * @remarks Can be used within scope of getLock() call. + */ + std::size_t size() const + { + return m_emitters.size(); + } + + /** + * Lock this object. + * This lock will be automatically released when out of scope (unless + * someone + * copies it). Do not use in the same scope as other API of this class. + * @return Lock object. + * @remarks Provided to allow locking emitters in scope of some client + * code. + */ + LockType getLock() + { + return LockType(new DPL::Mutex::ScopedLock(&m_mtx)); + } + + private: + typedef std::map Map; + typedef typename Map::iterator Iterator; + typedef typename Map::const_iterator ConstIterator; + + private: + DPL::Mutex m_mtx; ///< Synchronizes operation on this object. + Map m_emitters; ///< Emitters container. +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_EMITTERS_H_ diff --git a/src_wearable/Commons/EventListener.h b/src_wearable/Commons/EventListener.h new file mode 100644 index 0000000..abed4a9 --- /dev/null +++ b/src_wearable/Commons/EventListener.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ +#define WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ + +#include + +#include //TODO: temporary code: DPL::SharedPtr -> std::shared_ptr +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Base class for listeners. + * Object that is to act as listener should dervie from this class and implement + * OnAnswerReceived() function. + */ +template +class EventListener : private EventReceiver +{ + public: + EventListener(ThreadEnum::Enumeration threadType) : + EventReceiver(threadType) + {} + + virtual void onAnswerReceived(const DPL::SharedPtr& event) + { LogError("Pure virtual function call"); } //TODO: temporary code: DPL::SharedPtr -> std::shared_ptr + + virtual void onAnswerReceived(const std::shared_ptr& event) + { LogError("Pure virtual function call"); } //TODO: temporary code: DPL::SharedPtr -> std::shared_ptr + + void postAnswer(const DPL::SharedPtr& event) + { + DPL::Event::ControllerEventHandler >:: + PostEvent( + event); + } + + protected: + void OnEventReceived(const DPL::SharedPtr &event) + { + onAnswerReceived(event); + } +}; + +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ */ diff --git a/src_wearable/Commons/EventReceiver.h b/src_wearable/Commons/EventReceiver.h new file mode 100644 index 0000000..88b78d6 --- /dev/null +++ b/src_wearable/Commons/EventReceiver.h @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ +#define WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +template +class SignalEventCall : public DPL::Event::AbstractEventCall +{ + DPL::SharedPtr m_event; + + public: + + SignalEventCall(const DPL::SharedPtr &event) : m_event(event) + {} + virtual void Call() + { + _D("signaling in SignalEventCall"); + m_event->signalSynchronousEventFlag(); + } +}; + +template +class EventReceiver : + protected DPL::Event::Controller< + typename DPL::TypeListDecl >::Type> +{ + DPL::Event::ThreadEventDispatcher m_threadDispatcher; + + protected: + + EventReceiver(ThreadEnum::Enumeration threadType) + { + DPL::Thread *thread = + ThreadPool::getInstance().getThreadRef(threadType); + DPL::Event::ControllerEventHandler >:: + Touch(); + DPL::Event::ControllerEventHandler >:: + SwitchToThread(thread); + } + + void signalEventByDispatcher(const DPL::SharedPtr &event) + { + _D("called"); + Try { + DPL::Event::AbstractEventDispatcher *dispatcher = + ThreadPool::getInstance().getDispatcher(m_threadDispatcher); + dispatcher->AddEventCall(new SignalEventCall(event)); + } + Catch(DPL::Thread::Exception::UnmanagedThread) { + // if called on unmanaged thread, + // call signalSynchronousEventFlag() directly + _E("signalSynchronousEventFlag() is called" + "by unmanaged thread"); + event->signalSynchronousEventFlag(); + } + } + + virtual ~EventReceiver() + { + DPL::Event::ControllerEventHandler >:: + SwitchToThread(NULL); + } +}; + +template +class EventRequestReceiver : private EventReceiver +{ + public: + EventRequestReceiver(ThreadEnum::Enumeration threadType) : EventReceiver< + TemplateEvent>(threadType) + {} + virtual void OnRequestReceived(const DPL::SharedPtr &) + { LogError("Pure virtual function call"); } //TODO: temporary code: DPL::SharedPtr -> std::shared_ptr + + virtual void OnRequestReceived(const std::shared_ptr &) + { LogError("Pure virtual function call"); } + + /* + * + * @argument delaySeconds - event will be received not sooner than after + * delay (in seconds) + */ + void PostRequest(const DPL::SharedPtr &event, + double delaySeconds = 0.0) + { + _D("called"); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + assert(TemplateEvent::STATE_INITIAL == event->m_state); + event->m_state = TemplateEvent::STATE_REQUEST_SEND; + } + + if (TemplateEvent::HANDLING_SYNCHRONOUS == event->getHandlingType() && + !event->m_synchronousEventFlag) + { + event->m_synchronousEventFlag = new DPL::WaitableEvent(); + } + + if (0.0 == delaySeconds) { + DPL::Event::ControllerEventHandler > + :: + PostEvent(event); + } else { + DPL::Event::ControllerEventHandler > + :: + PostTimedEvent(event, delaySeconds); + } + + switch (event->getHandlingType()) { + case TemplateEvent::HANDLING_NOT_SET: + assert(0); + break; + case TemplateEvent::HANDLING_SYNCHRONOUS: + event->waitForAnswer(); + break; + } + } + + void OnEventReceived(const DPL::SharedPtr &event) + { + _D("called"); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + if (event->m_cancelled) { + event->handleCancel(); + event->m_cancelAllowed = true; + event->signalCancelStatusFlag(); + event->signalFinishedFlag(); + return; + } else { + assert( + TemplateEvent::STATE_REQUEST_SEND == event->m_state && + "Wrong state!"); + } + event->m_state = TemplateEvent::STATE_REQUEST_RECEIVED; + } + + OnRequestReceived(event); + event->signalCancelStatusFlag(); + //After Controller ends processing it should call it to signal that work + // is done + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + + if (event->m_cancelled) { + //if cancel was not handled in OnRequestReceived when we should + //process as if it was not cancelled at all. + if (event->m_cancelAllowed) { + event->handleCancel(); + event->signalFinishedFlag(); + return; + } + } + //when event is not in manual answer mode we will answer now + if (TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER != + event->m_handlingType && + TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER != + event->m_handlingType) + { + event->m_state = TemplateEvent::STATE_ANSWER_SEND; + } + } + + switch (event->m_handlingType) { + case TemplateEvent::HANDLING_NOT_SET: + assert(0); + break; + case TemplateEvent::HANDLING_SYNCHRONOUS: + //event->Signal(); + this->signalEventByDispatcher(event); + break; + case TemplateEvent::HANDLING_ASYNCHRONOUS: + ///TODO check - shouldn't it be in signalEventByDispatcher? + if (NULL != event->m_remoteController) { + event->m_remoteController->PostAnswer(event); + } + //event->Signal(); + this->signalEventByDispatcher(event); + break; + //when event is in manual answer mode we do nothing - the answer will be + // send explicit from the code + case TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER: + case TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER: + break; + } + } + + virtual void ManualAnswer(const DPL::SharedPtr &event) + { + _D("called"); + assert( + event->m_handlingType == + TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER || + event->m_handlingType == + TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + if (event->m_cancelled) { + //if cancel was not handled in OnRequestReceived when we should + //process as if it was not cancelled at all. + if (event->m_cancelAllowed) { + event->handleCancel(); + event->signalCancelStatusFlag(); + event->signalFinishedFlag(); + return; + } + } + event->m_state = TemplateEvent::STATE_ANSWER_SEND; + } + switch (event->m_handlingType) { + case TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER: + //event->Signal(); + this->signalEventByDispatcher(event); + break; + case TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER: + //event->Signal(); + if (NULL != event->m_remoteController) { + event->m_remoteController->PostAnswer(event); + } + this->signalEventByDispatcher(event); + break; + default: + break; + } + } +}; + +template +class EventAnswerReceiver : private EventReceiver +{ + public: + EventAnswerReceiver(ThreadEnum::Enumeration threadType) : EventReceiver< + TemplateEvent>(threadType) + {} + + virtual void OnAnswerReceived(const DPL::SharedPtr &) + { LogError("Pure virtual function call"); } //TODO: temporary code: DPL::SharedPtr -> std::shared_ptr + + virtual void OnAnswerReceived(const std::shared_ptr &) + { LogError("Pure virtual function call"); } + + //it should be hidden outside, but I can't do it! I can't! :| + void PostAnswer(const DPL::SharedPtr &event) + { + LogDebug(__FUNCTION__); + event->signalCancelStatusFlag(); + DPL::Event::ControllerEventHandler >:: + PostEvent( + event); + } + + void OnEventReceived(const DPL::SharedPtr &event) + { + _D("EventAnswerReceiver: answer received"); + //check if it can be processed and set the state + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + + //in case someone changed it to synchronous call, we don't process + // it + if (TemplateEvent::STATE_CHANGED_TO_SYNCHRONOUS == + event->m_state || TemplateEvent::STATE_ENDED == + event->m_state) + { + return; + } + //we should get cancelled or answer_send state here + assert( + TemplateEvent::STATE_ANSWER_SEND == event->m_state && + "Wrong state!"); + + if (event->m_cancelled && event->m_cancelAllowed) { + event->handleCancel(); + event->signalFinishedFlag(); + return; + } + event->m_state = TemplateEvent::STATE_ANSWER_RECEIVED; + } + + OnAnswerReceived(event); + + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + assert(TemplateEvent::STATE_ANSWER_RECEIVED == event->m_state); + event->m_state = TemplateEvent::STATE_ENDED; + delete event->m_cancelStatusFlag; + event->m_cancelStatusFlag = NULL; + //if someone is waiting + event->signalFinishedFlag(); + } + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ */ diff --git a/src_wearable/Commons/Exception.h b/src_wearable/Commons/Exception.h new file mode 100644 index 0000000..0f1db99 --- /dev/null +++ b/src_wearable/Commons/Exception.h @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ +#define WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +#define PLUGINS_DECLARE_EXCEPTION_TYPE(BaseClass, Class) \ + class Class : \ + public BaseClass \ + { \ + ExceptionCodes::Enumeration m_code; \ + public: \ + virtual ExceptionCodes::Enumeration getCode() const { return m_code; } \ + Class(const char *path, \ + const char *function, \ + int line, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, message) \ + { \ + BaseClass::m_className = #Class; \ + m_code = ExceptionCodes::Class; \ + } \ + \ + Class(const char *path, \ + const char *function, \ + int line, \ + const DPL::Exception & reason, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, reason, message) \ + { \ + BaseClass::m_className = #Class; \ + m_code = ExceptionCodes::Class; \ + } \ + }; + +class ExceptionCodes +{ + public: + enum Enumeration + { + None, + Exception, + InvalidArgumentException, + ConversionException, + NullPointerException, + UnknownException, + PlatformException, + OutOfRangeException, + EventCancelledException, + EventWrongStateException, + SecurityException, + UnsupportedException, + PlatformWrongStateException, + PendingOperationException, + AlreadyInUseException, + CameraCaptureException, + CameraLiveVideoException, + LocalStorageValueNoModifableException, + NotFoundException + }; +}; + +/** + * General exception. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(DPL::Exception, Exception) + +/** + * Thrown when passed argument is not of expected type. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, InvalidArgumentException) + +/** + * Thrown when type conversion is not possible. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, ConversionException) + +/** + * Thrown when trying to operate on an object which is set to NULL. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, NullPointerException) + +/** + * Thrown when unknown error occured. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, UnknownException) + +/** + * Thrown when platform function returned error code or threw an exception. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PlatformException) + +/** + * Thrown when trying to access out of range element from array + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, OutOfRangeException) + +/** + * Thrown when trying to operate on cancelled event + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, EventCancelledException) + +/** + * Thrown when trying to operate on event in wrong state + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, EventWrongStateException) + +/** + * Thrown when trying to perform some action w/o proper permissions. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, SecurityException) + +/** + * Thrown when trying to perform action that is not supported by current + * platform. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, UnsupportedException) + +/** + * Thrown when trying to perform action on platform in wrong state. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PlatformWrongStateException) + +/** + * Thrown when trying to perform asynchronous action on JS object + * that already executes other asynchronous operation. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PendingOperationException) + +/** + * Thrown when used camera is already in use. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, AlreadyInUseException) + +/** + * Thrown when unpredicted error occurs while a picture or video is being + * captured + * or if endRecording is called while no video is currently captured. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, CameraCaptureException) + +/** + * camera live video cannot be provided. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, CameraLiveVideoException) + +/** + * Error trying to modify read only value + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, LocalStorageValueNoModifableException) + +/** + * Thrown when object is not found. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, NotFoundException) +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ */ diff --git a/src_wearable/Commons/FunctionDeclaration.h b/src_wearable/Commons/FunctionDeclaration.h new file mode 100644 index 0000000..d603c49 --- /dev/null +++ b/src_wearable/Commons/FunctionDeclaration.h @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARATION_ +#define WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARATION_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define ACE_DECLARE_FUNCTION(function_definition) \ + extern WrtDeviceApis::Commons::AceFunction ace_##function_definition + +#define ACE_DECLARE_PARAM(param_definition) \ + extern WrtDeviceApis::Commons::AceDeviceCapParam ace_param_## \ + param_definition + +class DevCapFinder +{ + public: + explicit DevCapFinder(const std::string& devcap) : m_searchFor(devcap) + {} + explicit DevCapFinder(const char* devcap) : m_searchFor(devcap) + {} + bool operator()(const WrtDeviceApis::Commons::AceDeviceCapability& dc) + const + { + return m_searchFor == dc.devCapName; + } + + private: + std::string m_searchFor; +}; + +#define ACE_ADD_DEV_CAP_PARAM(dev_caps_list, dev_cap_name, param) \ + do { \ + WrtDeviceApis::Commons::AceDeviceCaps::iterator devcapit = \ + std::find_if(dev_caps_list.begin(), \ + dev_caps_list.end(), \ + DevCapFinder(dev_cap_name)); \ + if (devcapit == dev_caps_list.end()) \ + { \ + ThrowMsg( \ + WrtDeviceApis::Commons::InvalidArgumentException, \ + "Trying to set a param that doesn't exist: " << \ + dev_cap_name); \ + } \ + else \ + { \ + LogDebug("Setting dev cap " << dev_cap_name << " param: " << \ + param.name << " to value " << param.value); \ + devcapit->devCapParams.push_back(param); \ + } \ + } while (0) + +/* + * Macro must be run inside plugin function. Plugin function must follow this + * declaration: + * plugin_example_function(JScontextRef cotext, JSObjectRef function, + * JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + * JSValueRef *exception); + * where context, arguments, argumentsCount, exception are fixed and could not + * be change. + * */ + +#define DECLARE_FUNCTION_GETTER(Plugin_Module) \ + WrtDeviceApis::Commons::AceFunction get##Plugin_Module##FunctionData( \ + const std::string & functionId); + +#define DEFINE_FUNCTION_GETTER(Plugin_Module, FunctionMap) \ + WrtDeviceApis::Commons::AceFunction get##Plugin_Module##FunctionData( \ + const std::string & functionId) \ + { \ + WrtDeviceApis::Commons::FunctionMapping::const_iterator it = \ + FunctionMap.find(functionId); \ + if (it == FunctionMap.end()) \ + { \ + std::string errorMsg(); \ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, \ + "Function with id " << functionId << "not found"); \ + } \ + return it->second; \ + } + +typedef WrtDeviceApis::Commons::AceFunction (&AceFunctionGetter)(const std:: + string&); + +namespace WrtDeviceApis { +namespace Commons { +enum class AceSecurityStatus +{ + AccessGranted, + AccessDenied, + PrivacyDenied, + InternalError +}; + +template +class DefaultArgsVerifier +{ + public: + void operator()(AceFunction& aceFunction, Args && ... args) const + { + static_assert( + WrtDeviceApis::Commons::AlwaysFalse::value, + "Please provide a specialization for these argument types!"); + } +}; + +template <> +class DefaultArgsVerifier<> +{ + public: + void operator()(AceFunction& /*aceFunction*/) const + {} +}; + +template +AceSecurityStatus aceCheckAccess( + const FunctionGetter& f, + const char* functionName, + Args && ... args) +{ + using namespace WrtDeviceApis::Commons; + + AceFunction aceFunction = f(functionName); + + ArgumentsVerifier argsVerify; + argsVerify(aceFunction, args ...); + + WrtAccess::CheckAccessReturnType ret = + WrtAccessSingleton::Instance().checkAccessControl(aceFunction); + + if (ret == WrtAccess::CHECK_ACCESS_PRIVILEGE_DENIED) { + return AceSecurityStatus::AccessDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_PRIVACY_DENIED) { + return AceSecurityStatus::PrivacyDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_INTERNAL_ERROR) { + return AceSecurityStatus::InternalError; + } + + return AceSecurityStatus::AccessGranted; +} +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARARION_ diff --git a/src_wearable/Commons/FunctionDefinition.cpp b/src_wearable/Commons/FunctionDefinition.cpp new file mode 100644 index 0000000..4209994 --- /dev/null +++ b/src_wearable/Commons/FunctionDefinition.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "FunctionDefinition.h" + +namespace WrtDeviceApis { +namespace Commons { +int aceAddDeviceCap(const AceDeviceCapability& cap, + AceDeviceCaps &instance) +{ + instance.push_back(cap); + return 0; +} + +int aceAddApiFeature(const AceFeature& apiFeature, + AceFeatures& instance) +{ + instance.push_back(apiFeature); + return 0; +} +} +} // WrtDeviceApisCommon diff --git a/src_wearable/Commons/FunctionDefinition.h b/src_wearable/Commons/FunctionDefinition.h new file mode 100644 index 0000000..fa8b32c --- /dev/null +++ b/src_wearable/Commons/FunctionDefinition.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION_ +#define WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Creates an empty device cap list. Additional device-caps may be added by + * ACE_CREATE_DEVICE_CAP and ACE_ADD_DEVICE_CAP macros + */ +#define ACE_CREATE_DEVICE_CAPS_LIST(device) \ + WrtDeviceApis::Commons::AceDeviceCaps ace_##device + +/** + * Creates an empty api features list. Additional api features may be added by + * ACE_CREATE_FEATURE and ACE_ADD_API_FEATURE macros + */ +#define ACE_CREATE_FEATURE_LIST(apifeature) \ + WrtDeviceApis::Commons::AceFeatures ace_##apifeature + +/** + * Creates a device capability which should be later added to device cap list + */ +#define ACE_CREATE_DEVICE_CAP(device_cap_id, cap_id) \ + WrtDeviceApis::Commons::AceDeviceCapability ace_##device_cap_id = \ + AceDeviceCapability(cap_id, WrtDeviceApis::Commons::AceDeviceCapParams()); + +/** + * Create an api feature which should be later added to api features list + */ +#define ACE_CREATE_FEATURE(feature_id, feature_api) \ + WrtDeviceApis::Commons::AceFeature ace_##feature_id = { feature_api \ + }; + +/** + * Adds an existing device-cap created by ACE_CREATE_DEVICE_CAP macro to + * device cap list + */ +#define ACE_ADD_DEVICE_CAP(device, device_cap_id) \ + WrtDeviceApis::Commons::aceAddDeviceCap(ace_##device_cap_id, ace_##device) + +/** + * Adds an existing api feature created by ACE_CREATE_FEATURE macro to + * api feature list + */ +#define ACE_ADD_API_FEATURE(apifeature, feature_id) \ + WrtDeviceApis::Commons::aceAddApiFeature(ace_##feature_id, \ + ace_##apifeature) + +/** + * Creates a function definition with given id that uses provided api feature + * and device capability lists + */ +#define ACE_CREATE_FUNCTION(function_id, function_name, feature_id, device) \ + { function_name, ace_##feature_id, ace_##device } + +// Support for param:name begin +#define ACE_CREATE_PARAM(param_definition, param_name, position) \ + static WrtDeviceApis::Commons::AceDeviceCapParam ace_param_## \ + param_definition = \ + { std::string(param_name), position }; + +// Support for param:name end + +typedef std::map FunctionMapping; + +int aceAddDeviceCap(const AceDeviceCapability &cap, + AceDeviceCaps & instance); +int aceAddApiFeature(const AceFeature &apiFeature, + AceFeatures & instance); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION diff --git a/src_wearable/Commons/IEvent.h b/src_wearable/Commons/IEvent.h new file mode 100644 index 0000000..207f5bb --- /dev/null +++ b/src_wearable/Commons/IEvent.h @@ -0,0 +1,383 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_IEVENT_H_ +#define WRTDEVICEAPIS_COMMONS_IEVENT_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class IEventPrivateData +{ + public: + virtual ~IEventPrivateData() + {} +}; + +class IEventController +{ + DPL::SharedPtr m_privateData; + + public: + virtual void waitTillProcessed() = 0; + virtual void waitForAnswer() = 0; + virtual bool cancelRequest() + { + return false; + } + virtual bool changeCallToSynchronous() = 0; + virtual ~IEventController() + {} + + void setPrivateData( + const DPL::SharedPtr &privateData) + { + m_privateData = privateData; + } + const DPL::SharedPtr& getPrivateData() + { + return m_privateData; + } +}; +typedef DPL::SharedPtr IEventControllerPtr; + +// CRTP pattern +template +class IEvent : /*private DPL::WaitableEvent, */ public IEventController +{ + public: + friend class EventRequestReceiver; + friend class EventAnswerReceiver; + friend class SignalEventCall; + friend class EventReceiver; + + enum HandlingType + { + HANDLING_NOT_SET = -1, + HANDLING_SYNCHRONOUS = 0, + HANDLING_ASYNCHRONOUS = 1, + HANDLING_SYNCHRONOUS_MANUAL_ANSWER = 2, + HANDLING_ASYNCHRONOUS_MANUAL_ANSWER = 3 + }; + + enum State + { + STATE_INITIAL, + STATE_REQUEST_SEND, + STATE_REQUEST_RECEIVED, + STATE_ANSWER_SEND, + STATE_ANSWER_RECEIVED, + STATE_ENDED, + STATE_CHANGED_TO_SYNCHRONOUS + }; + + private: + void handleCancel() + { + clearOnCancel(); + m_state = STATE_ENDED; + m_exceptionCode = Commons::ExceptionCodes::EventCancelledException; + //if someone is waiting + signalSynchronousEventFlag(); + } + + protected: + DPL::Mutex m_stateMutex; + State m_state; + HandlingType m_handlingType; + EventAnswerReceiver< Super > *m_remoteController; + Commons::ExceptionCodes::Enumeration m_exceptionCode; + DPL::WaitableEvent *m_synchronousEventFlag; + DPL::WaitableEvent *m_finishedFlag; + DPL::WaitableEvent *m_cancelStatusFlag; + bool m_cancelSignalAhead; + bool m_cancelled; + bool m_cancelAllowed; + + IEvent() : + m_state(STATE_INITIAL), + m_handlingType(HANDLING_NOT_SET), + m_remoteController(NULL), + m_exceptionCode(Commons::ExceptionCodes::None), + m_synchronousEventFlag(NULL), + m_finishedFlag(NULL), + m_cancelStatusFlag(NULL), + m_cancelSignalAhead(false), + m_cancelled(false), + m_cancelAllowed(false) + {} + + virtual void waitForAnswer() + { + assert(HANDLING_SYNCHRONOUS == m_handlingType); + DPL::WaitForSingleHandle(m_synchronousEventFlag->GetHandle()); + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + m_state = STATE_ENDED; + } + signalFinishedFlag(); + LogDebug("deleting m_processEvent"); + delete m_synchronousEventFlag; + m_synchronousEventFlag = NULL; + } + + void signalFinishedFlag() + { + if (m_finishedFlag) { + m_finishedFlag->Signal(); + } + } + + DPL::WaitableEvent &getFinishedFlag() + { + if (!m_finishedFlag) { + m_finishedFlag = new DPL::WaitableEvent(); + } + return *m_finishedFlag; + } + + void signalCancelStatusFlag() + { + LogDebug("signaling cancel"); + DPL::Mutex::ScopedLock lock(&m_stateMutex); + m_cancelSignalAhead = true; + if (m_cancelStatusFlag) { + m_cancelStatusFlag->Signal(); + } + } + + DPL::WaitableEvent &getCancelStatusFlag() + { + if (!m_cancelStatusFlag) { + m_cancelStatusFlag = new DPL::WaitableEvent(); + } + return *m_cancelStatusFlag; + } + + void signalSynchronousEventFlag() + { + if (m_synchronousEventFlag) { + m_synchronousEventFlag->Signal(); + } + } + + public: + + /* + * Gets the answer receiver pointer. + */ + EventAnswerReceiver< Super > * getAnswerReceiverRef() const + { + return m_remoteController; + } + + virtual ~IEvent() + { + delete m_cancelStatusFlag; + delete m_finishedFlag; + delete m_synchronousEventFlag; + } + + virtual bool changeCallToSynchronous() + { + return setForSynchronousCall(); + } + + virtual void waitTillProcessed() + { + DPL::WaitForSingleHandle(getFinishedFlag().GetHandle()); + delete m_finishedFlag; + m_finishedFlag = NULL; + } + + virtual void clearOnCancel() + {} + + Commons::ExceptionCodes::Enumeration getExceptionCode() const + { + return m_exceptionCode; + } + void setExceptionCode(Commons::ExceptionCodes::Enumeration exceptionCode) + { + m_exceptionCode = exceptionCode; + } + + short getHandlingType() const + { + return m_handlingType; + } + + virtual bool setForSynchronousCall() + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + m_state = STATE_CHANGED_TO_SYNCHRONOUS; + break; + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + m_handlingType = HANDLING_SYNCHRONOUS; + return true; + } + + virtual bool setForAsynchronousCall( + EventAnswerReceiver< Super > *remoteController) + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + m_handlingType = HANDLING_ASYNCHRONOUS; + m_remoteController = remoteController; + return true; + } + + /* + * Normally, after invoking OnRequestReceived in RequestReceiver, the answer + * is being send automatically (after flow leaves OnRequestReceived). + * After calling this function, the answer is not being send automatically, + * you need to call ManualAnswer to send event back. + * It works both in asynchronous and synchronous handling type. + */ + virtual bool switchToManualAnswer() + { + assert( + m_handlingType == HANDLING_ASYNCHRONOUS || m_handlingType == + HANDLING_SYNCHRONOUS); + + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + + switch (m_handlingType) { + case HANDLING_ASYNCHRONOUS: + m_handlingType = HANDLING_ASYNCHRONOUS_MANUAL_ANSWER; + break; + case HANDLING_SYNCHRONOUS: + m_handlingType = HANDLING_SYNCHRONOUS_MANUAL_ANSWER; + break; + default: + break; + } + return true; + } + + bool checkCancelled() + { + //DPL::Mutex::ScopedLock lock(&m_stateMutex); + return m_cancelled; + } + + void tryCancelled() + { + //DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + Throw(Commons::EventCancelledException); + } + } + + bool getCancelAllowed() const + { + return m_cancelAllowed; + } + + void setCancelAllowed(bool cancelAllowed) + { + m_cancelAllowed = cancelAllowed; + } + + bool cancelRequest() + { + LogDebug("trying to cancel"); + assert(HANDLING_ASYNCHRONOUS == m_handlingType || + HANDLING_ASYNCHRONOUS_MANUAL_ANSWER == m_handlingType); + bool signaled = false; + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_INITIAL: + assert(0); + case STATE_ANSWER_SEND: + LogDebug("cancelling"); + m_cancelled = true; + delete m_cancelStatusFlag; + m_cancelStatusFlag = NULL; + return m_cancelAllowed; + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + LogDebug("cancelling"); + m_cancelled = true; + signaled = m_cancelSignalAhead; + if (!signaled) { + //create waitable handle + getCancelStatusFlag(); + } + } + LogDebug("waiting for cancel flag"); + if (!signaled) { + DPL::WaitForSingleHandle(getCancelStatusFlag().GetHandle()); + } + delete m_cancelStatusFlag; + m_cancelStatusFlag = NULL; + return m_cancelAllowed; + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_IEVENT_H_ */ diff --git a/src_wearable/Commons/IExternEventCanceler.h b/src_wearable/Commons/IExternEventCanceler.h new file mode 100644 index 0000000..958fdd6 --- /dev/null +++ b/src_wearable/Commons/IExternEventCanceler.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. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ +#define WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ + +#include + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * This class is related to JSPendingOperation object. + * + * It is interface for controllers which want to perform + * an additional accation when the PendingOberation object + * is canceled. + * */ +template +class IExternEventCanceler +{ + public: + virtual void OnCancelEvent(const std::shared_ptr& event) + { LogError("Pure virtual function call"); } + + virtual void OnCancelEvent(const DPL::SharedPtr& event) + { LogError("Pure virtual function call"); } + + virtual ~IExternEventCanceler() + {} +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ diff --git a/src_wearable/Commons/JSObject.cpp b/src_wearable/Commons/JSObject.cpp new file mode 100644 index 0000000..70488f1 --- /dev/null +++ b/src_wearable/Commons/JSObject.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "JSObject.h" +#include + +JSObject::JSObject(RealObject object) : m_object(object) +{ + if (!object) { + LogError("Object is NULL"); + } +} + +JSObject::RealObject JSObject::getObject() const +{ + return m_object; +} diff --git a/src_wearable/Commons/JSObject.h b/src_wearable/Commons/JSObject.h new file mode 100644 index 0000000..d52f5a8 --- /dev/null +++ b/src_wearable/Commons/JSObject.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_H_ + +#include +#include + +class JSObject : private DPL::Noncopyable +{ + public: + typedef void* RealObject; + + public: + explicit JSObject(RealObject object); + + /** + * returns javascript engine object + * @throw NullPtrException + * */ + virtual RealObject getObject() const; + + virtual ~JSObject() + {} + + private: + RealObject m_object; +}; + +typedef DPL::SharedPtr JSObjectPtr; + +#endif diff --git a/src_wearable/Commons/JSObjectDeclaration.cpp b/src_wearable/Commons/JSObjectDeclaration.cpp new file mode 100755 index 0000000..192040b --- /dev/null +++ b/src_wearable/Commons/JSObjectDeclaration.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object_declaration.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include "JSObjectDeclaration.h" + +JSObjectDeclaration::JSObjectDeclaration(js_entity_definition_ptr_t classD) : + m_name(classD->object_name), + m_parentName(classD->parent_name), + m_interfaceName(classD->interface_name), + m_classTemplate(NULL), + m_constructorCallback(classD->js_class_constructor_cb) +{ + if (NULL != classD->js_class_template_getter_fun) { + m_classTemplate = classD->js_class_template_getter_fun(); + } + if (classD->class_options) { + m_options = OptionsPtr(new Options(classD->class_options)); + } +} + +JSObjectDeclaration::~JSObjectDeclaration() +{} + +bool JSObjectDeclaration::checkIframesSupported() const +{ + if (!m_options || + m_options->getIframeObject() == Options::IFrameObject::None) + { + return false; + } + + return true; +} + +JSObjectDeclaration::Options::ClassType +JSObjectDeclaration::Options::getType() const +{ + AssertMsg(m_options, "Pointer to options is NULL"); + + switch (m_options->type) { + case JS_CLASS: return ClassType::Class; + case JS_FUNCTION: return ClassType::Function; + case JS_INTERFACE: return ClassType::Interface; + default: Assert(!"Wrong value of type"); + } +} + +JSObjectDeclaration::Options::IFrameObject +JSObjectDeclaration::Options::getIframeObject() const +{ + AssertMsg(m_options, "Options object is NULL"); + + switch (m_options->iframe_option) { + case NONE: return IFrameObject::None; + case REFERENCE: return IFrameObject::Reference; // deprecated + case CREATE_INSTANCE: return IFrameObject::CreateInstance; + default: + Assert(!"Wrong value of behaviour type"); + } +} + +JSObjectDeclaration::Options::IFrameNotice +JSObjectDeclaration::Options::getIframeNotice() const +{ + AssertMsg(m_options, "Pointer to options is null"); + + switch (m_options->iframe_notice) { + case NONE_NOTICE: return IFrameNotice::None; + case ALWAYS_NOTICE: return IFrameNotice::AlwaysNotice; + default: + Assert(!"Wrong value of notice option"); + } +} + +js_function_impl JSObjectDeclaration::Options::getFunctionImpl() const +{ + AssertMsg(m_options, "Pointer to options is null"); + return m_options->function; +} + +void JSObjectDeclaration::Options::invokeCallback(JsContext ctx, + ObjectInstance iframe, + ObjectInstance object) const +{ + LogDebug("JS Object create, notice."); + AssertMsg(m_options && m_options->cb, "Empty callback pointer"); + m_options->cb(ctx, iframe, object); +} + +JSObjectDeclaration::Options::PrivateData +JSObjectDeclaration::Options::getPrivateData() const +{ + AssertMsg(m_options && m_options->private_data, "empty private data"); + return m_options->private_data; +} diff --git a/src_wearable/Commons/JSObjectDeclaration.h b/src_wearable/Commons/JSObjectDeclaration.h new file mode 100644 index 0000000..a726029 --- /dev/null +++ b/src_wearable/Commons/JSObjectDeclaration.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_object_declaration.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_DECLARATION_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_DECLARATION_H_ + +#include +#include +#include +#include +#include +#include +#include + +class JSObjectDeclaration : private DPL::Noncopyable +{ + public: + typedef const void* ConstClassTemplate; + typedef void* ClassTemplate; + typedef js_class_constructor_cb_t ConstructorCallback; + typedef class_definition_options_t ClassOptions; + + class Options : DPL::Noncopyable + { + public: + enum class ClassType + { + Class, + Function, + Interface + }; + + enum class IFrameObject + { + None, + Reference, + CreateInstance + }; + + enum class IFrameNotice + { + None, + AlwaysNotice + }; + + //only for function + enum class IFrameOverlay + { + Ignored, + UseOverlayed, //deprecated + OverlayedBeforeOriginal //deprecated + }; + + typedef js_object_instance_t ObjectInstance; + typedef java_script_context_t JsContext; + typedef void* PrivateData; + + public: + ClassType getType() const; + + IFrameObject getIframeObject() const; + IFrameNotice getIframeNotice() const; + js_function_impl getFunctionImpl() const; + + void invokeCallback(JsContext ctx, + ObjectInstance iframe, + ObjectInstance object) const; + + PrivateData getPrivateData() const; + + private: + const ClassOptions* m_options; + + private: + explicit Options(const ClassOptions* options) : m_options(options) + { + assert(options && "Dont create empty options"); + } + + friend class JSObjectDeclaration; + }; + + typedef std::shared_ptr OptionsPtr; + + public: + + explicit JSObjectDeclaration(js_entity_definition_ptr_t declaration); + + virtual const std::string& getName() const + { + return m_name; + } + + virtual const std::string& getParentName() const + { + return m_parentName; + } + + virtual ConstClassTemplate getClassTemplate() const + { + return m_classTemplate; + } + + virtual const std::string& getInterfaceName() const + { + return m_interfaceName; + } + + virtual ConstructorCallback getConstructorCallback() const + { + return m_constructorCallback; + } + + const OptionsPtr getOptions() const + { + return m_options; + } + + bool checkIframesSupported() const; + + virtual ~JSObjectDeclaration(); + + private: + std::string m_name; + std::string m_parentName; + std::string m_interfaceName; + ConstClassTemplate m_classTemplate; + ConstructorCallback m_constructorCallback; + OptionsPtr m_options; +}; + +typedef DPL::SharedPtr JSObjectDeclarationPtr; + +#endif diff --git a/src_wearable/Commons/ListenerEvent.h b/src_wearable/Commons/ListenerEvent.h new file mode 100644 index 0000000..7956ab7 --- /dev/null +++ b/src_wearable/Commons/ListenerEvent.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ +#define WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +template +class ListenerEventEmitter; + +/** + * This is base class for events that should act as signals between abstract + * layer and layer that uses it (e.g. JS layer in WRT plugins). + * Such event is created by specific event emitter from abstract layer + * and passed asynchronously to object that acts as event listener. + * Template parameter should be class of an event which derives from + * this class (co called CRTP pattern). + */ +template +class ListenerEvent +{ + friend class ListenerEventEmitter; + + public: + typedef IEventPrivateData PrivateDataType; + typedef DPL::SharedPtr PrivateDataTypePtr; + + public: + virtual ~ListenerEvent() + { + delete m_mtx; + } + + /** + * Gets exception code. + * @return Exception code. + */ + Commons::ExceptionCodes::Enumeration getExceptionCode() const + { + DPL::Mutex::ScopedLock lock(m_mtx); + return m_code; + } + + /** + * Sets exception code. + * @param code Exception code. + * @throw EventWrongStateExeption When event has already been emitted. + */ + void setExceptionCode(Commons::ExceptionCodes::Enumeration code) + { + DPL::Mutex::ScopedLock lock(m_mtx); + m_code = code; + } + + /** + * Gets event's private data. + * @return Private data (use DPL cast to proper object). + */ + const PrivateDataTypePtr& getPrivateData() const + { + DPL::Mutex::ScopedLock lock(m_mtx); + return m_privateData; + } + + protected: + ListenerEvent() : + m_mtx(new DPL::Mutex()), + m_code(Commons::ExceptionCodes::None) + {} + + ListenerEvent(const ListenerEvent &ths) : + m_mtx(new DPL::Mutex()), + m_code(ths.m_code), + m_privateData(ths.m_privateData) + {} + + ListenerEvent& operator=(const ListenerEvent &other) + { + if (this != &other) { + m_mtx = new DPL::Mutex(); + m_code = other.m_code; + m_privateData = other.m_privateData; + } + return *this; + } + + /** + * Sets event's private data. + * Event's private data object has to implement @see IEventPrivateData + * interface. + * @param data Private data. + * @throw EventWrongStateExeption When event has already been emitted. + */ + void setPrivateData(const PrivateDataTypePtr& data) + { + DPL::Mutex::ScopedLock lock(m_mtx); + m_privateData = data; + } + + protected: + mutable DPL::Mutex *m_mtx; + Commons::ExceptionCodes::Enumeration m_code; ///< Exception code. + PrivateDataTypePtr m_privateData; ///< Private data. +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ diff --git a/src_wearable/Commons/ListenerEventEmitter.h b/src_wearable/Commons/ListenerEventEmitter.h new file mode 100644 index 0000000..77bada2 --- /dev/null +++ b/src_wearable/Commons/ListenerEventEmitter.h @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ +#define WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +template +class Emitters; + +/** + * Creates listener events in the abstraction layer in response to some + * asynchronous action. + * To enable passing events from abstract layer to layer that uses it, first + * proper event emitter should be registered in abstract layer by the layer + * that uses it. Then when some action happens in abstract layer event should be + * created and passed to this emitter's emit() function. Then emitter passes + * this event to proper listener. + * Template parameter should be class that derives from @see ListenerEvent. + */ +template +class ListenerEventEmitter : private DPL::Noncopyable +{ + public: + typedef EventClass EventType; + typedef DPL::SharedPtr EventPtrType; + typedef ListenerEventEmitter Type; + typedef typename ListenerEvent::PrivateDataType + EventPrivateDataType; + typedef typename ListenerEvent::PrivateDataTypePtr + EventPrivateDataTypePtr; + typedef EventListener ListenerType; + typedef uintptr_t IdType; + + /** + * Empty (NULL) value of emitter's Id. + */ + static const IdType emptyId; + + public: + ListenerEventEmitter() : m_listener(NULL) + {} + + public: + virtual ~ListenerEventEmitter() + {} + + /** + * Sets event's private data. + * Event's private data object has to implement @see IEventPrivateData + * interface. + * @param data Private data. + * @remarks Practically private dat should be only set at object creation + * and + * not chaged during this object lifetime. + */ + virtual void setEventPrivateData(const EventPrivateDataTypePtr& data) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_privateData = data; + } + + /** + * Gets event's private data. + * @return Private data. + */ + virtual EventPrivateDataTypePtr getEventPrivateData() + { + DPL::Mutex::ScopedLock lock(&m_mtx); + return m_privateData; + } + + /** + * Sets listener. + * Object set as listener has to implement @see EventListener interface. + * @param listener Listener object. + * @remarks Doesn't take ownership over this object. + * It's suggested to use singletons to have one listener for all + * events (no dynamic allocation overhead). + */ + virtual void setListener(ListenerType* listener) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_listener = listener; + } + + /** + * Emits event. + * @param event Event to emit. + */ + virtual void emit(const EventPtrType& event) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + EventPtrType copy(new EventType(*event.Get())); + if (m_listener) { + copy->setPrivateData(m_privateData); + m_listener->postAnswer(copy); + } + } + + /** + * Gets id. + * @return Event's id. + * @remarks Id is implemented as value of `this` pointer. + */ + virtual IdType getId() + { + return reinterpret_cast(this); + } + + protected: + DPL::Mutex m_mtx; ///< Mutex for thread-safety. + ListenerType* m_listener; ///< Event listener object. + EventPrivateDataTypePtr m_privateData; ///< Private data. +}; + +template +const typename ListenerEventEmitter::IdType ListenerEventEmitter< + EventClass>::emptyId = 0; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ diff --git a/src_wearable/Commons/Range.h b/src_wearable/Commons/Range.h new file mode 100644 index 0000000..ab731e1 --- /dev/null +++ b/src_wearable/Commons/Range.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_RANGE_H_ +#define WRTDEVICEAPIS_COMMONS_RANGE_H_ + +namespace WrtDeviceApis { +namespace Commons { +/** + * Stores data describing a range of values. + */ +template +struct Range +{ + /** + * Type of value. + */ + typedef Type ValueType; + + /** + * Value representing minimum. + */ + ValueType min; + + /** + * Value representing maximum. + */ + ValueType max; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_RANGE_H_ diff --git a/src_wearable/Commons/Regex.cpp b/src_wearable/Commons/Regex.cpp new file mode 100644 index 0000000..9284d3f --- /dev/null +++ b/src_wearable/Commons/Regex.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "Regex.h" + +namespace WrtDeviceApis { +namespace Commons { +bool validate(const std::string &pattern, + const std::string &value, + unsigned int options) +{ + pcrecpp::RE_Options pcreOpt; + if (options & VALIDATE_MATCH_CASELESS) { + pcreOpt.set_caseless(true); + } + pcrecpp::RE re(pattern, pcreOpt); + if (options & VALIDATE_MATCH_FULL) { + return re.FullMatch(value); + } + return re.PartialMatch(value); +} + +std::string filter(const std::string &pattern, + const std::string &value) +{ + pcrecpp::RE re(pattern); + std::string ret = static_cast(value); + re.GlobalReplace("", &ret); + return ret; +} + +std::string toUpper(const std::string &value) +{ + pcrecpp::RE re(LOWER_P); + std::string ret = static_cast(value); + re.GlobalReplace(UPPER_P, &ret); + return ret; +} +} +} // WrtDeviceApisCommon diff --git a/src_wearable/Commons/Regex.h b/src_wearable/Commons/Regex.h new file mode 100644 index 0000000..f6c046b --- /dev/null +++ b/src_wearable/Commons/Regex.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_REGEX_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +const unsigned int VALIDATE_MATCH_CASELESS = 0x0001; //use when you want to + // make caseless match +const unsigned int VALIDATE_MATCH_FULL = 0x0002; //use when you want + // supplied text + // matches a supplied + // pattern exactly +const std::string LOWER_P = "p"; +const std::string UPPER_P = "P"; + +/** + * Validates value against pattern + * @param pattern Regexp pattern + * @param value String to validate + * @param options Modifiers for a match. + * @return True when value is matched against pattern + */ +bool validate(const std::string &pattern, + const std::string &value, + unsigned int options = 0); + +/** + * Filter value against pattern(Any character except "0-9+#*Pp" will be removed + * from value) + * @param pattern Regexp pattern + * @param value String to be filtered + * @return filtered value + */ +std::string filter(const std::string &pattern, + const std::string &value); + +/** + * Replace character "p" in value by "P" + * @param value String to be replaced + * @return replaced value + */ +std::string toUpper(const std::string &value); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_H_ diff --git a/src_wearable/Commons/RegexPatterns.h b/src_wearable/Commons/RegexPatterns.h new file mode 100644 index 0000000..3c9ceb6 --- /dev/null +++ b/src_wearable/Commons/RegexPatterns.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +const std::string PATTERN_PHONE_NUMBER_FILTER("[^0-9+#*Pp]"); +const std::string PATTERN_PHONE_NUMBER("^[0-9#+*]+$"); +const std::string PATTERN_PHONE_NUMBER_P("^\\+?[0-9#*Pp]*[0-9][0-9#*Pp]*$"); +const std::string PATTERN_PHONE_NUMBER_PW("^[0-9#+*PpWw]+$"); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ diff --git a/src_wearable/Commons/RegexUtils.cpp b/src_wearable/Commons/RegexUtils.cpp new file mode 100644 index 0000000..db749e7 --- /dev/null +++ b/src_wearable/Commons/RegexUtils.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "RegexUtils.h" +#include +#include "StringUtils.h" + +namespace WrtDeviceApis { +namespace Commons { +std::string addStartPositionMark(const std::string &value) +{ + if (!String::startsWith(value, "^") && !String::startsWith(value, ".*")) { + return "^" + value; + } + return value; +} + +std::string addEndPositionMark(const std::string &value) +{ + if ((!String::endsWith(value, "$") || String::endsWith(value, "\\$")) && + !String::endsWith(value, ".*")) + { + return value + "$"; + } + return value; +} + +std::string addStartAndEndPositionMark(const std::string &value) +{ + return addEndPositionMark(addStartPositionMark(value)); +} + +std::string preparePercent(const std::string& str) +{ + std::string result = escape(str); + pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2\\\\*", &result); + pcrecpp::RE("(([^\\\\])%|^()%)").GlobalReplace("\\2.*", &result); + return result; +} + +std::string prepareAsterisk(const std::string& str) +{ + std::string result = escape(str); + // Replaces single wildcard "*" with version more compliant with Perl + // regular exrepssions, i.e. ".*". + pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2.*", &result); + return result; +} + +std::string escape(const std::string& str) +{ + std::string result = str; + // Escape standard regular expressions' metacharacters, + // i.e.: \, ., -, +, ?, (, ), [, ], ^, $, | + const char* metas = "(\\.|\\-|\\+|\\?|\\(|\\)|\\[|\\]|\\^|\\$|\\|" + "|(\\\\[^\\*\\%]|\\\\$))"; // \*, \% won't get + // additional '\' + pcrecpp::RE(metas).GlobalReplace("\\\\\\1", &result); + return result; +} +} +} // WrtDeviceApisCommon diff --git a/src_wearable/Commons/RegexUtils.h b/src_wearable/Commons/RegexUtils.h new file mode 100644 index 0000000..a06e1cd --- /dev/null +++ b/src_wearable/Commons/RegexUtils.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +/** + * Adds ^ character at the beginning in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addStartPositionMark(const std::string &value); + +/** + * Adds $ character at the end in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addEndPositionMark(const std::string &value); + +/** + * Adds ^ character at the beginning and $ the end in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addStartAndEndPositionMark(const std::string &value); + +/** + * Converts typical string with wildcard '%' to proper perl-like regular + * expression's pattern. + * @param str String that came from JS. + * @return Proper regular expression's pattern. + * @remarks Calling it twice will (probably?) cause double escaping. + */ +std::string preparePercent(const std::string& str); + +/** + * Converts typical string with wildcard '*' to proper perl-like regular + * expression's pattern. + * @param str String that came from JS. + * @return Proper regular expression's pattern. + * @remarks Calling it twice will (probably?) cause double escaping. + */ +std::string prepareAsterisk(const std::string& str); + +/** + * Escapes regex special characters. + * @param str String to escape. + * @return String with regex special characters escaped. + */ +std::string escape(const std::string& str); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ diff --git a/src_wearable/Commons/StaticAssert.h b/src_wearable/Commons/StaticAssert.h new file mode 100644 index 0000000..bbd19f2 --- /dev/null +++ b/src_wearable/Commons/StaticAssert.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file StaticAssert.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H +#define WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H + +namespace WrtDeviceApis { +namespace Commons { +template +struct CompileTimeChecker +{ + CompileTimeChecker(...); +}; + +template<> +struct CompileTimeChecker {}; + +#define STATIC_CHECK(expr, msg) \ + { \ + class ERROR_##msg {}; \ + CompileTimeChecker<(expr) != 0>((ERROR_##msg())); \ + } + +/** + * Define used to inform about errors in compilation time + * useful in templates + * @param msg - message to be displayed, + * msg have to be a valid C++ identifier, + * other way reported errors will be meaningless + * @param C - instance of object which caused problem + * error generated by compiler display type of C + * */ +#define STATIC_ERROR(msg, C) \ + { \ + C->_##msg(); \ + } +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H diff --git a/src_wearable/Commons/StringBuilder.cpp b/src_wearable/Commons/StringBuilder.cpp new file mode 100644 index 0000000..7fb1cb9 --- /dev/null +++ b/src_wearable/Commons/StringBuilder.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include +#include "Exception.h" +#include "StringBuilder.h" + +namespace WrtDeviceApis { +namespace Commons { +class StringBuilderImpl +{ + public: + StringBuilderImpl() : m_counter(1) + {} + + void append(const std::string& str) + { + if (!(m_ss << str)) { + m_ss.clear(); + ThrowMsg(PlatformException, "Couldn't append string."); + } + } + + void append(const StringBuilderImpl* impl) + { + if (!(m_ss << impl->m_ss)) { + m_ss.clear(); + ThrowMsg(PlatformException, + "Couldn't append string builder."); + } + } + + void addRef() + { + ++m_counter; + } + + void deref() + { + if (0 == --m_counter) { + delete this; + } + } + + StringBuilderImpl* clone() + { + if (1 == m_counter) { + return this; + } + + --m_counter; + + StringBuilderImpl* result = new StringBuilderImpl(); + result->m_ss << m_ss; + return result; + } + + std::string toString() const + { + return m_ss.str(); + } + + private: + std::stringstream m_ss; + unsigned int m_counter; +}; + +StringBuilder::StringBuilder() : m_impl(new StringBuilderImpl()) +{} + +StringBuilder::~StringBuilder() +{ + m_impl->deref(); +} + +StringBuilder::StringBuilder(const StringBuilder& other) +{ + other.m_impl->addRef(); + m_impl = other.m_impl; +} + +StringBuilder & StringBuilder::operator=(const StringBuilder& other) +{ + if (this == &other) { + return *this; + } + + other.m_impl->addRef(); + + m_impl->deref(); + m_impl = other.m_impl; + + return *this; +} + +StringBuilder& StringBuilder::append(const std::string& str) +{ + m_impl = m_impl->clone(); + m_impl->append(str); + return *this; +} + +StringBuilder& StringBuilder::append(const StringBuilder& builder) +{ + m_impl = m_impl->clone(); + m_impl->append(builder.m_impl); + return *this; +} + +std::string StringBuilder::toString() const +{ + return m_impl->toString(); +} +} +} // WrtDeviceApisCommon diff --git a/src_wearable/Commons/StringBuilder.h b/src_wearable/Commons/StringBuilder.h new file mode 100644 index 0000000..fa12c37 --- /dev/null +++ b/src_wearable/Commons/StringBuilder.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ +#define WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +class StringBuilderImpl; + +class StringBuilder +{ + public: + StringBuilder(); + StringBuilder(const StringBuilder& other); + ~StringBuilder(); + + StringBuilder& operator=(const StringBuilder& other); + + StringBuilder& append(const std::string& str); + StringBuilder& append(const StringBuilder& builder); + std::string toString() const; + + private: + StringBuilderImpl* m_impl; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ diff --git a/src_wearable/Commons/StringUtils.cpp b/src_wearable/Commons/StringUtils.cpp new file mode 100644 index 0000000..0b432b6 --- /dev/null +++ b/src_wearable/Commons/StringUtils.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include "StringUtils.h" + +namespace WrtDeviceApis { +namespace Commons { +namespace String { +std::string lTrim(const std::string& str) +{ + std::string result = str; + result.erase(result.begin(), + std::find_if(result.begin(), result.end(), + std::not1(std::ptr_fun(std::isspace)))); + return result; +} + +std::string rTrim(const std::string& str) +{ + std::string result = str; + result.erase(std::find_if(result.rbegin(), result.rend(), + std::not1(std::ptr_fun( + std::isspace))).base(), result.end()); + return result; +} + +std::string trim(const std::string& str) +{ + return lTrim(rTrim(str)); +} + +bool startsWith(const std::string& str, + const std::string& startStr) +{ + return str.find(startStr) == 0; +} + +bool endsWith(const std::string& str, + const std::string& endStr) +{ + std::size_t pos = str.rfind(endStr); + if (pos == std::string::npos) { + return false; + } + return pos == str.length() - endStr.length(); +} + +std::string unique(const std::string& str, + const char needle) +{ + std::string result = str; + + std::string::size_type pos = 0; + while ((pos = result.find_first_of(needle, pos)) < std::string::npos) { + std::string::size_type last = result.find_first_not_of(needle, pos); + if (last == std::string::npos) { + last = result.size(); + } + if (last - pos > 1) { + result.erase(pos + 1, last - pos - 1); + } + pos = last; + } + + return result; +} + +bool inCStringArray(const std::string& needle, + const char* stack[]) +{ + while (*stack) { + if (needle == *stack) { + return true; + } + ++stack; + } + return false; +} + +char* strdup(const char* str) +{ + char* result = ::strdup(str); + if (NULL == result) { + throw std::bad_alloc(); + } + return result; +} + +std::string merge(const std::vector& strs, + std::string::value_type delim) +{ + typedef std::vector Strings; + + std::ostringstream ss; + if (!strs.empty()) { + for (Strings::size_type i = 0; i < strs.size() - 1; ++i) { + ss << strs[i] << delim; + } + ss << strs.at(strs.size() - 1); + } + return ss.str(); +} + +std::vector split(const std::string& str, + std::string::value_type delim) +{ + std::vector result; + std::string::size_type begin = 0, end = 0; + while ((end = str.find_first_of(delim, begin))) { + std::string part = (std::string::npos == end ? + str.substr(begin) : + str.substr(begin, end - begin)); + if (!part.empty()) { + result.push_back(part); + } + if (std::string::npos == end) { + break; + } + begin = end + 1; + } + return result; +} + +int toInt(const std::string& str) +{ + return convertTo(str); +} +} +} +} diff --git a/src_wearable/Commons/StringUtils.h b/src_wearable/Commons/StringUtils.h new file mode 100644 index 0000000..b36071f --- /dev/null +++ b/src_wearable/Commons/StringUtils.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file StringUtils.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STRINGUTILS_H_ +#define WRTDEVICEAPIS_COMMONS_STRINGUTILS_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +namespace String { +/** + * Removes spaces from begining of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string lTrim(const std::string& str); + +/** + * Removes spaces from end of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string rTrim(const std::string& str); + +/** + * Removes spaces from begining and end of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string trim(const std::string& str); + +/** + * Checks if str starts with startStr + * @param str String to be searched. + * @param startStr String to be found at the beginning of str. + * @return true when str starts with startStr, false otherwise. + */ +bool startsWith(const std::string& str, const std::string& startStr); + +/** + * Checks if str ends with startStr + * @param str String to be searched. + * @param endStr String to be found at the end of str. + * @return true when str starts with startStr, false otherwise. + */ +bool endsWith(const std::string& str, const std::string& endStr); + +/** + * Merges consecutive groups of duplicate characters into one. + * @param str String to remove characters from. + * @param needle Character for which groups of duplicates to merge. + * @return String with group of duplicate characters merged. + * @code + * ... + * std::string str = "Aala maa kota"; + * std::string uniq = unique(str, 'a'); + * uniq == "Ala ma kota"; + * ... + * @endcode + */ +std::string unique(const std::string& str, const char needle); + +/** + * Checks if supplied string exists in specified array of c-strings. + * @param needle String to verify. + * @param stack Array of c-strings which last element should be NULL. + * @return True if string exists in array, false otherwise. + * @remarks Last element of array should be NULL, otherwise there is no + * way to calculate its number of elements. + */ +bool inCStringArray(const std::string& needle, const char* stack[]); + +/** + * Duplicates a string. + * @param str String to duplicate. + * @return String copy. + * @throw std::bad_alloc If allocation fails. + * @remarks Ownership passed to the caller. String has to be deallocated using + * free() function. + */ +char* strdup(const char* str); +inline char* strdup(const std::string& str) +{ + return strdup(str.c_str()); +} + +std::string merge(const std::vector& strs, + std::string::value_type delim); + +std::vector split(const std::string& str, + std::string::value_type delim); + +/** + * @deprecated Use convertTo(). + */ +int toInt(const std::string& str) WRT_PLUGINS_DEPRECATED; + +/** + * Converts string to specified type. + * + * @tparam T Type to convert to. + * @param str String to convert. + * @return Converted value. + * @throw ConversionException If conversion fails. + * + * @remarks T must implement default constructor and an implementation + * of input string operator for T must exist. + */ +template +T convertTo(const std::string& str) +{ + T result; + std::istringstream iss(str); + if (!(iss >> result)) { + Throw(ConversionException); + } + return std::move(result); +} + +/** + * Converts a given value to string. + * + * @tparam T Type of the value to convert. It is deduced by the compiler. + * @param data Value to convert. + * @return Value converted to string. + * @throw ConversionException If operation fails. + * + * @remarks Output stream operator for type T must exist. + */ +template +std::string parse(const T& data) +{ + std::ostringstream oss; + if (!(oss << data)) { + Throw(ConversionException); + } + return oss.str(); +} +} +} +} + +#endif diff --git a/src_wearable/Commons/ThreadPool.cpp b/src_wearable/Commons/ThreadPool.cpp new file mode 100644 index 0000000..fd5cd3a --- /dev/null +++ b/src_wearable/Commons/ThreadPool.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * ControllersFactory.cpp + * + * Created on: 2010-06-28 + * Author: kmajewski + */ + +#include + +#include +#include + +#include "ThreadPool.h" +#include "Exception.h" + +namespace WrtDeviceApis { +namespace Commons { +ThreadPool &ThreadPool::getInstance() +{ + static ThreadPool theInstance; + return theInstance; +} + +DPL::Event::AbstractEventDispatcher *ThreadPool::getDispatcher( + DPL::Event::ThreadEventDispatcher &callingThreadDispatcher) +{ + DPL::Thread *currentThread = DPL::Thread::GetCurrentThread(); + //if we are in main thread + if (NULL == currentThread) { + return &DPL::Event::GetMainEventDispatcherInstance(); + } + callingThreadDispatcher.SetThread(currentThread); + return &callingThreadDispatcher; +} + +ThreadPool::ThreadPool() +{} + +ThreadPool::~ThreadPool() +{ + for (ThreadHandleMap::const_iterator it = m_threadHandlers.begin(); it + != m_threadHandlers.end(); ++it) + { + delete (*it).second; + } +} + +DPL::Thread* ThreadPool::getThreadHandleCreateIfNotExists( + ThreadEnum::Enumeration type) +{ + DPL::Mutex::ScopedLock lock(&m_threadHandlersMutex); + ThreadHandleMap::iterator element = m_threadHandlers.find(type); + + //if element does not exists in the map + if (m_threadHandlers.end() == element) { + DPL::Thread* newThread = new DPL::Thread(); + m_threadHandlers.insert( + m_threadHandlers.begin(), + std::pair(type, newThread)); + newThread->Run(); + return newThread; + } + return (*element).second; +} + +DPL::Thread *ThreadPool::getThreadRef(ThreadEnum::Enumeration type) +{ + DPL::Thread *thandle = NULL; + if (type < 0 || type >= ThreadEnum::size) { + Throw(InvalidArgumentException); + } + /* we could stay with + * getThreadHandleCreateIfNotExists(type); + * but by switch we can attach actually one thread to more than one + * ThreadEnums + */ + switch (type) { + case ThreadEnum::NULL_THREAD: + thandle = NULL; + break; + case ThreadEnum::CAMERA_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CAMERA_THREAD); + break; + case ThreadEnum::CALENDAR_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CALENDAR_THREAD); + break; + case ThreadEnum::TELEPHONY_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::TELEPHONY_THREAD); + break; + case ThreadEnum::APPLAUNCHER_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::APPLAUNCHER_THREAD); + break; + case ThreadEnum::APPCONFIG_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::APPCONFIG_THREAD); + break; + case ThreadEnum::MESSAGING_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::FILESYSTEM_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::FILESYSTEM_THREAD); + break; + case ThreadEnum::GALLERY_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::GALLERY_THREAD); + break; + case ThreadEnum::CONTACT_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CONTACT_THREAD); + break; + case ThreadEnum::BONDI_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::BONDI_THREAD); + break; + case ThreadEnum::GEOLOCATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::GEOLOCATION_THREAD); + break; + case ThreadEnum::DEVICESTATUS_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::DEVICESTATUS_THREAD); + break; + case ThreadEnum::PROFILE_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::HAPTICS_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::ACCELEROMETER_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::ACCELEROMETER_THREAD); + break; + case ThreadEnum::ORIENTATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::ORIENTATION_THREAD); + break; + case ThreadEnum::TASK_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::TASK_THREAD); + break; + case ThreadEnum::POWER_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::POWER_THREAD); + break; + case ThreadEnum::PLUGIN_TEMPLETE_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::PLUGIN_TEMPLETE_THREAD); + break; + case ThreadEnum::BLUETOOTH_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::BLUETOOTH_THREAD); + break; + case ThreadEnum::APPLICATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::APPLICATION_THREAD); + break; + case ThreadEnum::GYROSCOPE_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::GYROSCOPE_THREAD); + break; + case ThreadEnum::CLOCK_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CLOCK_THREAD); + break; + case ThreadEnum::SYSTEMINFO_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::SYSTEMINFO_THREAD); + break; + case ThreadEnum::CALLHISTORY_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::CALLHISTORY_THREAD); + break; + case ThreadEnum::ACCOUNT_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::CALLHISTORY_THREAD); + break; + case ThreadEnum::NFC_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::NFC_THREAD); + break; + case ThreadEnum::MEDIACONTENT_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::MEDIACONTENT_THREAD); + break; + case ThreadEnum::SE_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::SE_THREAD); + break; + case ThreadEnum::DOWNLOAD_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::DOWNLOAD_THREAD); + break; + case ThreadEnum::PUSH_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::PUSH_THREAD); + break; + case ThreadEnum::SYNC_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::SYNC_THREAD); + break; + // ..... + default: + LogError("no case statement for ThreadEnum"); + Throw(InvalidArgumentException); + } + return thandle; +} +} +} // WrtDeviceApisCommon diff --git a/src_wearable/Commons/ThreadPool.h b/src_wearable/Commons/ThreadPool.h new file mode 100644 index 0000000..9d0bb57 --- /dev/null +++ b/src_wearable/Commons/ThreadPool.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * ControllersFactory.h + * + * Created on: 2010-06-28 + * Author: kmajewski + */ + +#ifndef WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ +#define WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class ThreadEnum +{ + private: + ThreadEnum() + {} + + public: + enum Enumeration + { + NULL_THREAD = 0, + CAMERA_THREAD, + CALENDAR_THREAD, + TELEPHONY_THREAD, + APPLAUNCHER_THREAD, + MESSAGING_THREAD, + FILESYSTEM_THREAD, + UI_THREAD, + APPCONFIG_THREAD, + GALLERY_THREAD, + CONTACT_THREAD, + BONDI_THREAD, + GEOLOCATION_THREAD, + DEVICESTATUS_THREAD, + PROFILE_THREAD, + HAPTICS_THREAD, + ACCELEROMETER_THREAD, + ORIENTATION_THREAD, + TASK_THREAD, + POWER_THREAD, + PLUGIN_TEMPLETE_THREAD, + BLUETOOTH_THREAD, + APPLICATION_THREAD, + GYROSCOPE_THREAD, + CLOCK_THREAD, + SYSTEMINFO_THREAD, + CALLHISTORY_THREAD, + ACCOUNT_THREAD, + NFC_THREAD, + MEDIACONTENT_THREAD, + SE_THREAD, + DOWNLOAD_THREAD, + PUSH_THREAD, + SYNC_THREAD, + //.... + size + }; +}; + +class ThreadPool : private DPL::Noncopyable +{ + private: + typedef std::map ThreadHandleMap; + ThreadHandleMap m_threadHandlers; + DPL::Mutex m_threadHandlersMutex; + + DPL::Thread *getThreadHandleCreateIfNotExists(ThreadEnum::Enumeration type); + + //DPL::MainEventDispatcher m_mainEventDispatcher; + + ThreadPool(); + + public: + ~ThreadPool(); + + /* + * @throws: WrtDeviceApis::Commons::InvalidArgumentException + */ + DPL::Thread * getThreadRef(ThreadEnum::Enumeration type); + + /* + * Get proper dispatcher for current calling thread + */ + DPL::Event::AbstractEventDispatcher *getDispatcher( + DPL::Event::ThreadEventDispatcher &callingThreadDispatcher); + + static ThreadPool& getInstance(); +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ diff --git a/src_wearable/Commons/TimeUtils.cpp b/src_wearable/Commons/TimeUtils.cpp new file mode 100644 index 0000000..ce5cce8 --- /dev/null +++ b/src_wearable/Commons/TimeUtils.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TimeUtils.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + */ + +#include "TimeUtils.h" +#include + +namespace WrtDeviceApis { +namespace Commons { +namespace Time { +struct tm* localtime_r(long long int* timep, struct tm* result) +{ + UErrorCode status = U_ZERO_ERROR; + UCalendar *cal; + + if (!result || !timep) { + return NULL; + } + + cal = ucal_open(NULL, 0, NULL, UCAL_DEFAULT, &status); + + if (U_FAILURE(status)) { + return NULL; + } + + ucal_setMillis(cal, (*timep * (double)1000.0), &status); + + result->tm_sec = ucal_get(cal, UCAL_SECOND, &status); + result->tm_min = ucal_get(cal, UCAL_MINUTE, &status); + result->tm_hour = ucal_get(cal, UCAL_HOUR, &status); + result->tm_mday = ucal_get(cal, UCAL_DAY_OF_MONTH, &status); + result->tm_mon = ucal_get(cal, UCAL_MONTH, &status); + result->tm_year = ucal_get(cal, UCAL_YEAR, &status); + result->tm_wday = ucal_get(cal, UCAL_DAY_OF_WEEK, &status); + result->tm_yday = ucal_get(cal, UCAL_DAY_OF_YEAR, &status); + result->tm_isdst = ucal_get(cal, UCAL_DST_OFFSET, &status); + + ucal_close(cal); + + if (U_FAILURE(status)) { + return NULL; + } else { + return result; + } +} +} +} +} diff --git a/src_wearable/Commons/TimeUtils.h b/src_wearable/Commons/TimeUtils.h new file mode 100644 index 0000000..de55e4c --- /dev/null +++ b/src_wearable/Commons/TimeUtils.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TimeUtils.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_TIMEUTILS_H_ +#define WRTDEVICEAPIS_COMMONS_TIMEUTILS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +namespace Time { +struct tm* localtime_r(long long int* timep, struct tm* result); +} +} +} +#endif diff --git a/src_wearable/Commons/TypeTraits.h b/src_wearable/Commons/TypeTraits.h new file mode 100644 index 0000000..bcc98f7 --- /dev/null +++ b/src_wearable/Commons/TypeTraits.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ +#define WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ + +#include + +namespace WrtDeviceApis { +namespace Commons { +template +struct IsNull +{ + static bool value(const T&) + { + return false; + } +}; + +template +struct IsNull +{ + static bool value(T* ptr) + { + return ptr == NULL; + } +}; + +template +struct IsNull > +{ + static bool value(const DPL::SharedPtr& ptr) + { + return ptr.Get() == NULL; + } +}; + +template +struct AlwaysFalse +{ + static const bool value = false; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ diff --git a/src_wearable/Commons/TypesDeclaration.h b/src_wearable/Commons/TypesDeclaration.h new file mode 100644 index 0000000..0f2dca2 --- /dev/null +++ b/src_wearable/Commons/TypesDeclaration.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONS_TYPES_DECLARATION_ +#define WRTDEVICEAPIS_COMMONS_TYPES_DECLARATION_ + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +struct AceFeature +{ + AceFeature(const std::string& featName) : name(featName) {} + std::string name; +}; + +typedef std::vector AceFeatures; + +struct AceDeviceCapParam +{ + AceDeviceCapParam(const std::string& parName, + const std::string& parVal) : name(parName), + value(parVal) + {} + + std::string name; + std::string value; +}; + +typedef std::vector AceDeviceCapParams; + +struct AceDeviceCapability +{ + AceDeviceCapability() {} + AceDeviceCapability(const std::string& name, + const AceDeviceCapParams& params) : + devCapName(name), + devCapParams(params) + {} + + std::string devCapName; + AceDeviceCapParams devCapParams; +}; + +typedef std::vector AceDeviceCaps; + +struct AceFunction +{ + std::string name; + AceFeatures features; + AceDeviceCaps deviceCapabilities; +}; +} // namespace Commons +} // namespace WrtDeviceApis + +#endif diff --git a/src_wearable/Commons/WrtAccess/WrtAccess.cpp b/src_wearable/Commons/WrtAccess/WrtAccess.cpp new file mode 100644 index 0000000..782d701 --- /dev/null +++ b/src_wearable/Commons/WrtAccess/WrtAccess.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "WrtAccess.h" +#include +#include + +#include "popup-runner.h" +IMPLEMENT_SAFE_SINGLETON(WrtDeviceApis::Commons::WrtAccess) + +namespace { +/** + * Helper class - single parameter and its value + */ +struct AceParam +{ + const char *name; + const char *value; + + AceParam() : + name(NULL), value(NULL) + {} + + AceParam(const char *name, const char *value) : + name(name), value(value) + {} +}; + +/** + * Helper class - list of params for single dev cap + */ +struct AceParamList +{ + size_t count; + AceParam* param; + AceParamList() : + count(0), + param(NULL) + {} +}; + +struct DeviceCapParamPolicy +{ + typedef AceParamList* Type; + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + if (ptr) { + delete[] ptr->param; + } + delete[] ptr; + } +}; + +/** + * Helper class - modified ScopedArray for ace_param_list_t + */ +class ScopedDeviceCapArray : public DPL::ScopedResource +{ + public: + explicit ScopedDeviceCapArray(AceParamList *ptr = + DeviceCapParamPolicy::NullValue()) : + DPL::ScopedResource(ptr) + {} + + AceParamList & operator [](std::ptrdiff_t k) const + { + AssertMsg(this->m_value != DeviceCapParamPolicy::NullValue(), + "Dereference of scoped NULL array!"); + AssertMsg(k >= 0, "Negative array index"); + + return this->m_value[k]; + } +}; +} // namespace + +namespace WrtDeviceApis { +namespace Commons { +WrtAccess::WrtAccess() : + m_sessionId(GenerateSessionId()), + m_pluginOwners(0) +{} + +WrtAccess::~WrtAccess() +{} + +WrtAccess::SessionId WrtAccess::GenerateSessionId() +{ + const size_t SESSION_ID_LENGTH = 32; + + std::ostringstream pid; + pid << static_cast(getpid()); + + std::string session_id = pid.str(); + + session_id.reserve(session_id.length() + SESSION_ID_LENGTH); + + for (size_t i = 0; i < SESSION_ID_LENGTH; ++i) { + int c = random() % 16; + + session_id += (c < 10 ? + static_cast('0' + c) : + static_cast('A' + c - 10)); + } + return session_id; +} + +void WrtAccess::initialize(int widgetId) +{ + _D("initialize"); + if (widgetId < 0) { + _E("Invalid widget id"); + Throw(Exception); + } + + m_widgetId = widgetId; + + if (!m_pluginOwners++) { + DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON"); + ace_return_t ret = ace_client_initialize(Wrt::Popup::run_popup); + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + Assert(ACE_OK == ret); + } +} + +void WrtAccess::deinitialize(int /*widgetId*/) +{ + _D("deinitialize"); + + if (!--m_pluginOwners) { + DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON"); + ace_return_t ret = ace_client_shutdown(); + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + Assert(ACE_OK == ret); + } +} + +int WrtAccess::getWidgetId() const +{ + return m_widgetId; +} + +WrtAccess::CheckAccessReturnType WrtAccess::checkAccessControl(const AceFunction& aceFunction) const +{ + AssertMsg( + m_pluginOwners, "WrtAccessSingleton needs to be initialized with" + "WidgetId during on_widget_start_callback in each plugin"); + size_t deviceCount = aceFunction.deviceCapabilities.size(); + + DPL::ScopedArray deviceScopedArray; + ScopedDeviceCapArray paramsScopedArray; + + if (deviceCount) { + deviceScopedArray.Reset(new const char*[deviceCount]); + paramsScopedArray.Reset(new AceParamList[deviceCount]); + + for (size_t i = 0; i < deviceCount; ++i) { + deviceScopedArray[i] = + aceFunction.deviceCapabilities.at(i).devCapName.c_str(); + paramsScopedArray[i].count = + aceFunction.deviceCapabilities.at(i).devCapParams.size(); + + paramsScopedArray[i].param = + new AceParam[paramsScopedArray[i].count]; + + for (size_t j = 0; j < paramsScopedArray[i].count; ++j) { + paramsScopedArray[i].param[j].name = + aceFunction.deviceCapabilities.at(i). + devCapParams[j].name.c_str(); + paramsScopedArray[i].param[j].value = + aceFunction.deviceCapabilities.at(i). + devCapParams[j].value.c_str(); + } + } + } + + size_t featuresCount = aceFunction.features.size(); + + DPL::ScopedArray featureScopedArray; + if (featuresCount) { + featureScopedArray.Reset(new const char*[featuresCount]); + + for (size_t i = 0; i < featuresCount; ++i) { + featureScopedArray[i] = + aceFunction.features.at(i).name.c_str(); + } + } + + _D("constructing ACE request"); + + ace_request_t aceRequest; + aceRequest.session_id = + const_cast(m_sessionId.c_str()); + aceRequest.widget_handle = getWidgetId(); + aceRequest.feature_list.count = featuresCount; + aceRequest.feature_list.items = + const_cast(featureScopedArray.Get()); + aceRequest.dev_cap_list.count = deviceCount; + aceRequest.dev_cap_list.items = new ace_dev_cap_t[deviceCount]; + + const char** devCapNames = deviceScopedArray.Get(); + AceParamList* paramList = paramsScopedArray.Get(); + + unsigned int i; + for (i = 0; i < deviceCount; ++i) { + aceRequest.dev_cap_list.items[i].name = + const_cast(devCapNames[i]); + aceRequest.dev_cap_list.items[i].param_list.count = paramList[i].count; + aceRequest.dev_cap_list.items[i].param_list.items = + new ace_param_t[paramList[i].count]; + unsigned int j; + for (j = 0; j < paramList[i].count; ++j) { + aceRequest.dev_cap_list.items[i].param_list.items[j].name = + const_cast(paramList[i].param[j].name); + aceRequest.dev_cap_list.items[i].param_list.items[j].value = + const_cast(paramList[i].param[j].value); + } + } + + ace_check_result_t aceCheckResult = ACE_PRIVILEGE_DENIED; + DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON"); + ace_return_t ret = ace_check_access_ex(&aceRequest, &aceCheckResult); + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + for (i = 0; i < deviceCount; ++i) { + delete[] aceRequest.dev_cap_list.items[i].param_list.items; + } + delete[] aceRequest.dev_cap_list.items; + + if (ACE_OK != ret) { + _E("Error in ace check: %d", static_cast(ret)); + return CHECK_ACCESS_INTERNAL_ERROR; + } + + if (aceCheckResult == ACE_ACCESS_GRANTED) { + return CHECK_ACCESS_GRANTED; + } + else if (aceCheckResult == ACE_PRIVILEGE_DENIED) { + return CHECK_ACCESS_PRIVILEGE_DENIED; + } + else if (aceCheckResult == ACE_PRIVACY_DENIED) { + return CHECK_ACCESS_PRIVACY_DENIED; + } + + return CHECK_ACCESS_INTERNAL_ERROR; +} +} +} // WrtDeviceApisCommon diff --git a/src_wearable/Commons/WrtAccess/WrtAccess.h b/src_wearable/Commons/WrtAccess/WrtAccess.h new file mode 100644 index 0000000..18893a0 --- /dev/null +++ b/src_wearable/Commons/WrtAccess/WrtAccess.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ACCESS_H_ +#define WRT_PLUGINS_WRT_ACCESS_H_ + +#include + +#include +#include + +namespace WrtDeviceApis { +namespace Commons { +class WrtAccess +{ + public: + enum CheckAccessReturnType + { + CHECK_ACCESS_GRANTED, + CHECK_ACCESS_PRIVILEGE_DENIED, + CHECK_ACCESS_PRIVACY_DENIED, + CHECK_ACCESS_INTERNAL_ERROR + }; + + void initialize(int widgetId); + void deinitialize(int widgetId); + int getWidgetId() const; + CheckAccessReturnType checkAccessControl(const AceFunction &aceFunction) const; + + private: + + typedef std::string SessionId; + SessionId GenerateSessionId(); + + WrtAccess(); + virtual ~WrtAccess(); + + int m_widgetId; + SessionId m_sessionId; + size_t m_pluginOwners; + + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton WrtAccessSingleton; +} +} // WrtDeviceApisCommon + +#endif //WRT_PLUGINS_WRT_ACCESS_H_ diff --git a/src_wearable/Commons/WrtAccess/config.cmake b/src_wearable/Commons/WrtAccess/config.cmake new file mode 100644 index 0000000..a31ce63 --- /dev/null +++ b/src_wearable/Commons/WrtAccess/config.cmake @@ -0,0 +1,5 @@ +get_current_path() + +set(SRCS_WRT_ACCESS + ${CURRENT_PATH}/WrtAccess.cpp +) diff --git a/src_wearable/Commons/plugin_initializer_def.h b/src_wearable/Commons/plugin_initializer_def.h new file mode 100644 index 0000000..73a6185 --- /dev/null +++ b/src_wearable/Commons/plugin_initializer_def.h @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief This is a file that you provides interface for wrt-engine while + * loading and using plugin + * If you are a plugin developer you need to plugin_initializer.cpp + * in your module and provide implementation for macros below + */ + +#ifndef WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ +#define WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ + +#include + +typedef java_script_context_t JavaScriptContext; + +#define EXPORT_SYMBOL __attribute__((__visibility__("default"))) + +//DEFINES FOR GLOBAL OBJECTS AVAILABLE IN JAVASCRIPT +/** + * each object which declare this object as parent + * will ba available as global object in javascript + */ +#define WRT_JS_EXTENSION_OBJECT_GLOBAL "GLOBAL_OBJECT" + +/** + * global object bondi + * */ +#define WRT_JS_EXTENSION_OBJECT_BONDI "bondi" + +/** + * global object Widget + * */ +#define WRT_JS_EXTENSION_OBJECT_WIDGET "Widget" + +/** + * global object deviceapis + * */ +#define WRT_JS_EXTENSION_OBJECT_DEVICEAPIS "deviceapis" + +/** + * global object tizen + * */ +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +//HAVE TO BE IMPLEMENTED IN EVERY PLUGIN +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while loading each widget (for every + * loaded widget this function will be called) + * Example: + * plugin_initializer.cpp + * void on_widget_start_callback(int widgetId, JSContextRef context, + * const engine_interface_t *interface) + * { + * //... + * } + * PLUGIN_ON_WIDGET_START(on_widget_start_callback) + */ +#define PLUGIN_ON_WIDGET_START(CALLBACK_NAME) extern "C" const \ + on_widget_start_proc PLUGIN_WIDGET_START_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while loading each widget + * (for every loaded widget this function will be called) + * Example: + * plugin_initializer.cpp + * void on_widget_init_callback(feature_mapping_interface_t *mapping) + * { + * //... + * } + * PLUGIN_ON_WIDGET_INIT(on_widget_init_callback) + */ +#define PLUGIN_ON_WIDGET_INIT(CALLBACK_NAME) extern "C" \ + const on_widget_init_proc PLUGIN_WIDGET_INIT_PROC EXPORT_SYMBOL = \ + CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while unloading each widget (for + * every unloaded widget this function will be called) + * Example: + * void on_widget_stop_callback(int widgetId) + * { + * //... + * } + * PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + */ +#define PLUGIN_ON_WIDGET_STOP(CALLBACK_NAME) extern "C" const \ + on_widget_stop_proc PLUGIN_WIDGET_STOP_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while unloading each page (for every + * loaded page, including nested page, this function will be called) + * Example: + * void on_frame_load_callback(java_script_context_t context) + * { + * //... + * } + * PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) + */ +#define PLUGIN_ON_FRAME_LOAD(CALLBACK_NAME) extern "C" const on_frame_load_proc \ + PLUGIN_FRAME_LOAD_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while ununloading each page (for + * every unloaded page, including nested page, this function will be called) + * Example: + * void on_frame_unload_callback(java_script_context_t context) + * { + * //... + * } + * PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + */ +#define PLUGIN_ON_FRAME_UNLOAD(CALLBACK_NAME) extern "C" const \ + on_frame_unload_proc PLUGIN_FRAME_UNLOAD_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) define an array of structures in your + * plugin_initializer.cpp(!) file describing a JS class (class_definition) and + * it's parent class name (parent_name). + * JS class will be bind to a parent class name (parent_name.jsclass_name). + * Example: + * plugin_initializer.cpp + * PLUGIN_CLASS_MAP_BEGIN + * PLUGIN_CLASS_MAP_ADD_CLASS( + * "bondi", + * WrtPluginBondi::JSICameraManager::getClassInfo()) + * PLUGIN_CLASS_MAP_ADD_CLASS( + * "bondi", + * WrtPluginBondi::JSICameraAnotherClass::getClassInfo()) + * PLUGIN_CLASS_MAP_END + * + */ +#define PLUGIN_CLASS_MAP_BEGIN extern "C" const js_entity_definition_t \ + PLUGIN_CLASS_MAP[] EXPORT_SYMBOL = { + +#define PLUGIN_CLASS_MAP_ADD_INTERFACE(PARENTNAME, \ + INTERFACENAME, \ + JSPRODUCTCLASSTEMPLATE, \ + PRODUCTCONSTRUCTORCB, \ + PRIVDATA) \ + { PARENTNAME, INTERFACENAME, "", JSPRODUCTCLASSTEMPLATE, \ + PRODUCTCONSTRUCTORCB, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_ADD_INTERFACE_PRODUCT(PARENTNAME, OBJECTNAME, \ + INTERFACENAME, PRIVDATA) \ + { PARENTNAME, OBJECTNAME, INTERFACENAME, NULL, NULL, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_ADD_CLASS(PARENTNAME, CLASSNAME, JSCLASSTEMPLATE, \ + PRIVDATA) \ + { PARENTNAME, CLASSNAME, "", JSCLASSTEMPLATE, NULL, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_END { NULL, NULL, NULL, NULL, NULL, NULL } }; + +#define PLUGIN_CLASS_MAP_BEGIN_STATIC static const js_entity_definition_t \ + PLUGIN_CLASS_MAP[] = { + +#define PLUGIN_GET_CLASS_MAP(CALLBACK_NAME) extern "C" const \ + get_widget_entity_map_proc \ + PLUGIN_GET_CLASS_PROC_MAP EXPORT_SYMBOL = CALLBACK_NAME; + +#endif // WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ diff --git a/src_wearable/CommonsJavaScript/CMakeLists.txt b/src_wearable/CommonsJavaScript/CMakeLists.txt new file mode 100755 index 0000000..ecd0317 --- /dev/null +++ b/src_wearable/CommonsJavaScript/CMakeLists.txt @@ -0,0 +1,84 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_JS}) +endmacro() + + +pkg_search_module(webkit2 REQUIRED ewebkit2) + +set(TARGET_NAME ${TARGET_COMMONS_JAVASCRIPT}) + +include_directories(${DIR_JS_COMMONS} + ${wrt-plugin-api_INCLUDE_DIRS} + ${webkit2_INCLUDE_DIRS}} + ) + + +set(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/Converter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ScopedJSStringRef.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSCallbackManager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ScopedJSStringRef.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Validator.cpp + # wrapper for simple version of aceCheckAcces + ${CMAKE_CURRENT_SOURCE_DIR}/Security/SecurityFunctionDeclaration.cpp + #ECMA Script Exception + ${CMAKE_CURRENT_SOURCE_DIR}/JSDOMException.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/DOMExceptionData.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSDOMExceptionFactory.cpp + #Pending Operation support + ${CMAKE_CURRENT_SOURCE_DIR}/JSPendingOperation.cpp +) + + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${webkit2_LIBRARIES} + ${TARGET_COMMONS} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}) + +#utils +install_header_file(PrivateObject.h) +#tools +install_header_file(Converter.h) +install_header_file(Validator.h) +install_header_file(JSUtils.h) +install_header_file(ScopedJSStringRef.h) +#callback manager +install_header_file(JSCallbackManager.h) +#exceptions +install_header_file(JSDOMException.h) +install_header_file(JSDOMExceptionFactory.h) +install_header_file(DOMExceptionData.h) +install_header_file(SecurityExceptions.h) +#static declarations +install_header_file(Security/StaticDeclaration.h) +install_header_file(Security/SecurityFunctionDeclaration.h) +#pending operation +install_header_file(SupportPendingOperation.h) +install_header_file(Utils.h) +install_header_file(JSPendingOperation.h) +install_header_file(JSPendingOperationPrivateObject.h) + diff --git a/src_wearable/CommonsJavaScript/Converter.cpp b/src_wearable/CommonsJavaScript/Converter.cpp new file mode 100644 index 0000000..0eccb60 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Converter.cpp @@ -0,0 +1,390 @@ +/* + * 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 +#include +#include +#include +#include "ScopedJSStringRef.h" +#include "Converter.h" +#include + +using namespace WrtDeviceApis::Commons; + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +Converter::Converter(JSContextRef context) : m_context(context) +{} + +Converter::~Converter() +{} + +JSObjectRef Converter::toJSObjectRef(const JSValueRef& arg) +{ + if (!arg) { + Throw(NullPointerException); + } + JSValueRef exception = NULL; + JSObjectRef result = JSValueToObject(m_context, arg, &exception); + if ((NULL == result) || (NULL != exception)) { + ThrowMsg(ConversionException, "Couldn't convert to a JS Object."); + } + return result; +} + +bool Converter::toBool(const JSValueRef& arg) +{ + return JSValueToBoolean(m_context, arg); +} + +unsigned char Converter::toUChar(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(static_cast(static_cast(tmp)))); +} + +char Converter::toChar(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(static_cast(static_cast(tmp)))); +} + +int Converter::toInt(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(static_cast(tmp))); +} + +int Converter::toInt(const std::string &arg) +{ + return static_cast(static_cast(toNumber_(arg))); +} + +long Converter::toLong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(static_cast(tmp))); +} + +long long Converter::toLongLong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +unsigned long Converter::toULong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(static_cast(tmp))); +} + +std::size_t Converter::toSizeT(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast(tmp)); +} + +std::size_t Converter::toSizeT(const JSStringRef& arg) +{ + return static_cast(toNumber_(arg)); +} + +double Converter::toDouble(const JSValueRef& arg) +{ + return toNumber_(arg); +} + +std::string Converter::toString(int arg) +{ + return toString_(arg); +} + +std::string Converter::toString(unsigned long arg) +{ + return toString_(arg); +} + +std::string Converter::toString(long arg) +{ + return toString_(arg); +} + +std::string Converter::toString(std::size_t arg) +{ + return toString_(arg); +} + +std::string Converter::toString(const JSValueRef& arg) +{ + return toString_(arg); +} + +std::string Converter::tryString(const JSValueRef& arg) +{ + if (!JSValueIsString(m_context, arg) && + !JSValueIsNumber(m_context, arg) && + !JSValueIsBoolean(m_context, arg)) + { + ThrowMsg(ConversionException, + "Argument is not convertable to JS String."); + } + + return toString_(arg); +} + +std::string Converter::toDateString(const JSValueRef& arg) +{ + if (!JSValueIsObject(m_context, arg)) { + ThrowMsg(ConversionException, "Argument is not JS Date."); + } + + return toString_(arg); +} + +std::string Converter::toString(const JSStringRef& arg) +{ + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(arg); + if (jsSize > 0) { + jsSize = jsSize + 1; + DPL::ScopedArray buffer(new char[jsSize]); + size_t written = JSStringGetUTF8CString(arg, buffer.Get(), jsSize); + if (written > jsSize) { + ThrowMsg(ConversionException, + "Conversion could not be fully performed."); + } + result = buffer.Get(); + } + + return result; +} + +time_t Converter::toDateTimeT(const JSValueRef& arg) +{ + struct tm tm = toDateTm(arg); + return mktime(&tm); +} + +tm Converter::toDateTm(const JSValueRef& arg) +{ + std::string stringDate = toDateString(arg); + struct tm result; + char* currentLocale = setlocale(LC_TIME, NULL); + if (currentLocale == NULL) { + ThrowMsg(ConversionException, "Couldn't get current locale."); + } + DPL::ScopedFree currentLocaleCopy(strdup(currentLocale)); + if (setlocale(LC_TIME, "C") == NULL) { + ThrowMsg(ConversionException, "Couldn't set POSIX locale."); + } + if (strptime(stringDate.c_str(), "%a %b %d %Y %T", &result) == NULL) { + ThrowMsg(ConversionException, "Couldn't convert supplied date."); + } + if (setlocale(LC_TIME, currentLocaleCopy.Get()) == NULL) { + ThrowMsg(ConversionException, "Couldn't set previous locale back."); + } + //strptime function doesn't affect tm_isdst flag. + //It may cause -1hr conversion error. Setting it to -1 informs that + //there is no information about daylight saving time. + result.tm_isdst = -1; + return result; +} + +std::vector Converter::toVectorOfUChars(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toUChar); +} + +std::vector Converter::toVectorOfChars(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toChar); +} + +std::vector Converter::toVectorOfInts(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toInt); +} + +std::vector Converter::toVectorOfStrings(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toString); +} + +std::vector Converter::toVectorOfTimeT(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toDateTimeT); +} + +JSValueRef Converter::toJSValueRef(bool arg) +{ + return JSValueMakeBoolean(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(unsigned int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(unsigned long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRefLong(const long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(long long int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(double arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(const std::string& arg) +{ + JSValueRef result = NULL; + JSStringRef jsString = JSStringCreateWithUTF8CString(arg.c_str()); + result = JSValueMakeString(m_context, jsString); + JSStringRelease(jsString); + return result; +} + +JSValueRef Converter::toJSValueRef(const tm& arg) +{ + JSValueRef args[6]; + args[0] = JSValueMakeNumber(m_context, arg.tm_year + 1900); + args[1] = JSValueMakeNumber(m_context, arg.tm_mon); + args[2] = JSValueMakeNumber(m_context, arg.tm_mday); + args[3] = JSValueMakeNumber(m_context, arg.tm_hour); + args[4] = JSValueMakeNumber(m_context, arg.tm_min); + args[5] = JSValueMakeNumber(m_context, arg.tm_sec); + + JSValueRef exception = NULL; + JSObjectRef result = JSObjectMakeDate(m_context, 6, args, &exception); + if (NULL != exception) { + ThrowMsg(ConversionException, "Couldn't convert to a JS Date."); + } + + return result; +} + +JSValueRef Converter::toJSValueRef(const time_t arg) +{ + struct tm tminfo; + memset(&tminfo,0,sizeof(tminfo)); + localtime_r(&arg, &tminfo); + return toJSValueRef(tminfo); +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(const char* arg) +{ + return toJSValueRef(std::string(arg)); +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(JSValueRef arg) +{ + return arg; +} + +JSValueRef Converter::toJSValueRef(const std::vector& arg) +{ + return toJSValueRef_(arg); +} + +JSStringRef Converter::toJSStringRef(const std::string& arg) +{ + return JSStringCreateWithUTF8CString(arg.c_str()); +} + +double Converter::toNumber_(const JSStringRef& arg) +{ + return toNumber_(toString(arg)); +} + +double Converter::toNumber_(const std::string& arg) +{ + double result; + std::stringstream ss(arg); + if (!(ss >> result)) { + Throw(ConversionException); + } + return result; +} + +double Converter::toNumber_(const JSValueRef& arg) +{ + JSValueRef exception = NULL; + double result = JSValueToNumber(m_context, arg, &exception); + if (NULL != exception) { + ThrowMsg(ConversionException, "Couldn't convert to a number."); + } + return result; +} + +std::string Converter::toString_(const JSValueRef& arg) +{ + std::string result; + + JSValueRef exception = NULL; + JSStringRef str = JSValueToStringCopy(m_context, arg, &exception); + if (NULL == str) { + ThrowMsg(ConversionException, "Couldn't cast to a string."); + } + + size_t jsSize = JSStringGetMaximumUTF8CStringSize(str); + if (jsSize > 0) { + DPL::ScopedArray buffer(new char[jsSize]); + JSStringGetUTF8CString(str, buffer.Get(), jsSize); + result = buffer.Get(); + } + JSStringRelease(str); + return result; +} + +bool Converter::isNan(double value) const +{ + // This should work unless -ffast-math (GCC) option is used. + STATIC_CHECK(std::numeric_limits::is_iec559, + NOT_IEEE754_REPRESENTATION); + return (value != value); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src_wearable/CommonsJavaScript/Converter.h b/src_wearable/CommonsJavaScript/Converter.h new file mode 100644 index 0000000..ff196b6 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Converter.h @@ -0,0 +1,585 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class Converter : private DPL::Noncopyable +{ + public: + explicit Converter(JSContextRef context); + virtual ~Converter(); + + /** + * Converts JSValueRef to JSObjectRef. + * @param arg JSValueRef object to convert. + * @return JSObjectRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSObjectRef toJSObjectRef(const JSValueRef& arg); + + /** + * Converts JSValueRef object to boolean value. + * @param arg JSValueRef object to convert. + * @return Boolean value. + * @throw ConversionException Thrown when conversion fails. + */ + bool toBool(const JSValueRef& arg); + + /** + * Converts JSValueRef object to unsigned char value. + * @param arg JSValueRef object to convert. + * @return Unsigned char value. + * @throw ConversionException Thrown when conversion fails. + */ + unsigned char toUChar(const JSValueRef& arg); + + /** + * Converts JSValueRef object to char value. + * @param arg JSValueRef object to convert. + * @return Char value. + * @throw ConversionException Thrown when conversion fails. + */ + char toChar(const JSValueRef& arg); + + /** + * Converts JSValueRef to integer value. + * @param arg JSValueRef object to convert. + * @return Integer value. + * @throw ConversionException Thrown when conversion fails. + */ + int toInt(const JSValueRef& arg); + + /** + * Converts string to integer value. + * @param arg string to convert. + * @return Integer value. + * @throw ConversionException Thrown when conversion fails. + */ + int toInt(const std::string& arg); + + /** + * Converts JSvalueRef to long integer value. + * @param arg JSValueRef object to convert. + * @return Long integer value. + * @throw ConversionException Thrown when conversion fails. + */ + long toLong(const JSValueRef& arg); + + /** + * Converts JSvalueRef to long long integer value. + * @param arg JSValueRef object to convert. + * @return Long long integer value. + * @throw ConversionException Thrown when conversion fails. + */ + long long toLongLong(const JSValueRef& arg); + /** + * Converts JSValueRef to unsigned long value. + * @param arg JSValueRef object to convert. + * @return Unsigned long value. + * @throw ConversionException Thrown when conversion fails. + */ + unsigned long toULong(const JSValueRef& arg); + + /** + * Converts JSValueRef to double value. + * @param arg JSValueRef object to convert. + * @return Double value. + * @throw ConversionException Thrown when conversion fails. + */ + double toDouble(const JSValueRef& arg); + + /** + * Converts JSValueRef to size_t value. + * @param arg JSValueRef object to convert. + * @return Size_t value. + * @throw ConversionException Thrown when conversion fails. + */ + std::size_t toSizeT(const JSValueRef& arg); + + /** + * Converts JSStringRef to size_t value. + * @param arg JSStringRef object to convert. + * @return Size_t value. + * @throw ConversionException Thrown when conversion fails. + */ + std::size_t toSizeT(const JSStringRef& arg); + + /** + * Converts int to STL string. + * @param arg int to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toString(int arg); + + std::string toString(unsigned long arg); + + std::string toString(long arg); + + std::string toString(std::size_t arg); + + /** + * Converts JSValueRef to STL string. + * @param arg JSValueRef to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + * @remarks If one wants to convert JS Date object to a string then + * toDateString() should be used. + */ + std::string toString(const JSValueRef& arg); + + /** + * Converts JSStringRef to STL string. + * @param arg JSStringRef to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toString(const JSStringRef& arg); + + /** + * Converts JSSValueRef to STL string if + * arg is one of: String, Number, Bool + * @param arg JSValueReg to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string tryString(const JSValueRef& arg); + + /** + * Converts JS Date object to STL string. + * @param arg JS Date object to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toDateString(const JSValueRef& arg); + + /** + * Converts JSValueRef to time_t value. + * @param arg JSValueRef to convert. + * @return time_t value. + * @throw ConversionException Thrown when conversion fails. + */ + time_t toDateTimeT(const JSValueRef& arg); + + /** + * Converts JSValueRef to tm struct. + * @param arg JSValueRef to convert. + * @return tm struct. + * @throw ConversionException Thrown when conversion fails. + */ + tm toDateTm(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector. + * @param arg JSValueRef to convert. + * @return vector. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfUChars(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector. + * @param arg JSValueRef to convert. + * @return vector. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfChars(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector. + * @param arg JSValueRef to convert. + * @return vector. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfInts(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector of string. + * @param arg JSValueRef to convert. + * @return std::vector + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfStrings(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector of time_t. + * @param arg JSValueRef to convert. + * @return std::vector + * @throw ConversionException Thrown when conversion fails. + */ + std::vector toVectorOfTimeT(const JSValueRef& arg); + + /** + * Converts boolean value to JSValueRef. + * @param arg Boolean value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(bool arg); + + /** + * Converts integer value to JSValueRef. + * @param arg Integer value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(int arg); + + /** + * Converts unsigned integer value to JSValueRef. + * @param arg Unsigned integer value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(unsigned int arg); + + /** + * Converts double value to JSValueRef. + * @param arg Double value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(double arg); + + /** + * Converts unsigned long value to JSValueRef. + * @param arg unsigned long value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(unsigned long arg); + + /** + * Converts long value to JSValueRef. + * @param arg long value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRefLong(const long arg); + + /** + * Converts unsigned long value to JSValueRef. + * @param arg long long int value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(long long int arg); + + /** + * Converts STL string to JSValueRef. + * @param arg STL string to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::string& arg); + + /** + * Converts char sequence to JSValueRef. + * @param arg char sequence to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const char* arg); + + /** + * Converts time_t value to JSValueRef. + * @param arg time_t value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const time_t arg); + + /** + * Converts tm struct to JSValueRef. + * @param arg tm struct to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const tm& arg); + + /** + * Converts STL vector of integer to JSValueRef. + * @param arg STL vector of integer to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Converts STL vector of time_t to JSValueRef. + * @param arg STL vector of time_t to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Converts STL vector of string to JSStringRef. + * @param arg STL string to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Converts JSValueRef to JSValueRef + * @param JSValueRef js value which is returned + * @return JSValueRef - parameter + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(JSValueRef arg); + + /** + * Converts std::vector to JSValueRef + * @param arg vecotr of JSValueRefs + * @return JSValueRef - js array + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector& arg); + + /** + * Template specialization to catch errors caused + * by wrong usage of general template or + * implicit conversions from SharedPtr to + * specialized type + * */ + template + JSValueRef toJSValueRef(const DPL::SharedPtr& c) + { + STATIC_ERROR(ERROR_INVALID_IMPLICIT_CONVERSION, c) + //above macro causes compilation error + return static_cast(NULL); + } + + /** + * Converts STL string to JSStringRef. + * @param arg STL string to convert. + * @return JSStringRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSStringRef toJSStringRef(const std::string& arg); + + protected: + bool isNan(double value) const; + + double toNumber_(const JSValueRef& arg); + + double toNumber_(const JSStringRef& arg); + + double toNumber_(const std::string& arg); + + template + std::vector toVectorOfT_(const JSValueRef& arg, + T (Derived::*f)(const JSValueRef &), + Derived* object) + { + if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) + { + return std::vector(); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "Argument is not an JS array."); + } + + std::vector result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back((object->*f)(element)); + } + return result; + } + + template + std::vector toVectorOfT_(const JSValueRef& arg, + T (Converter::*f)(const JSValueRef &)) + { + if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) + { + return std::vector(); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "Argument is not an JS array."); + } + + std::vector result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back((this->*f)(element)); + } + return result; + } + + template + JSValueRef toJSValueRef_(const std::vector& arg, + JSValueRef (Derived::*f)(const T &), + Derived* object) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = (object->*f)(arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template + JSValueRef toJSValueRef_(const std::vector& arg) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = toJSValueRef(arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template + JSValueRef toJSValueRef_(const std::list& arg) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + typename std::list::const_iterator it = arg.begin(); + for (std::size_t i = 0; it != arg.end(); ++i, ++it) { + JSValueRef tmpVal = toJSValueRef(*it); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template + JSValueRef toJSValueRef_(const std::list& arg, + JSValueRef (Derived::*f)(const T &), + Derived* object) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + typename std::list::const_iterator it = arg.begin(); + for (std::size_t i = 0; it != arg.end(); ++i, ++it) { + JSValueRef tmpVal = (object->*f)(*it); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + std::string toString_(const JSValueRef& arg); + + template + std::string toString_(const T& arg) + { + std::stringstream ss; + if (!(ss << arg)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, + "Could not convert to string."); + } + return ss.str(); + } + + protected: + JSContextRef m_context; +}; + +template +class ConverterFactory : private DPL::Noncopyable +{ + public: + /** + * Converter type which deletes itself when gets out of scope. + */ + typedef DPL::SharedPtr ConverterType; + + public: + /** + * Gets converter object. + * @param context JavaScript context the conversion will be performed in. + * @param[out] exception JavaScript value for storing exception. + * @return Converter object. + */ + static ConverterType getConverter(JSContextRef context) + { + C* convert = new C(context); + return ConverterType(convert); + } + + private: + ConverterFactory(); +}; + +typedef ConverterFactory BasicConverterFactory; + +typedef BasicConverterFactory::ConverterType BasicConverter; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ */ diff --git a/src_wearable/CommonsJavaScript/DESCRIPTION b/src_wearable/CommonsJavaScript/DESCRIPTION new file mode 100644 index 0000000..7f04546 --- /dev/null +++ b/src_wearable/CommonsJavaScript/DESCRIPTION @@ -0,0 +1 @@ +Common code diff --git a/src_wearable/CommonsJavaScript/DOMExceptionData.cpp b/src_wearable/CommonsJavaScript/DOMExceptionData.cpp new file mode 100644 index 0000000..3eb148a --- /dev/null +++ b/src_wearable/CommonsJavaScript/DOMExceptionData.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "DOMExceptionData.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +DOMExceptionData::DOMExceptionData(int code, + const std::string& message) : + m_code(code), + m_message(message) +{} + +int DOMExceptionData::getCode() const +{ + return m_code; +} + +std::string DOMExceptionData::getMessage() const +{ + return m_message; +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_wearable/CommonsJavaScript/DOMExceptionData.h b/src_wearable/CommonsJavaScript/DOMExceptionData.h new file mode 100644 index 0000000..b6cd760 --- /dev/null +++ b/src_wearable/CommonsJavaScript/DOMExceptionData.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_DOM_EXCEPTION_DATA_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_DOM_EXCEPTION_DATA_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class DOMExceptionData +{ + public: + explicit DOMExceptionData(int code, + const std::string& message = std::string()); + + int getCode() const; + std::string getMessage() const; + + private: + int m_code; + std::string m_message; +}; + +typedef DPL::SharedPtr DOMExceptionDataPtr; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // WRT_DOM_EXCEPTION_DATA_H_ diff --git a/src_wearable/CommonsJavaScript/JSCallbackManager.cpp b/src_wearable/CommonsJavaScript/JSCallbackManager.cpp new file mode 100644 index 0000000..900d21a --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSCallbackManager.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file JSCallbackManager.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#include "JSCallbackManager.h" +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +JSCallbackManagerPtr JSCallbackManager::createObject( + JSContextRef context, + JSValueRef onSuccess, + JSValueRef onError, + bool + acceptJSNullAsOnSuccess, + bool acceptJSNullAsOnError) +{ + JSObjectRef l_onSuccess = NULL; + JSObjectRef l_onError = NULL; + + if (NULL != onSuccess && + (!acceptJSNullAsOnSuccess || !JSValueIsNull(context, onSuccess))) + { + l_onSuccess = JSValueToObject(context, onSuccess, NULL); + if (!l_onSuccess || + !JSObjectIsFunction(context, l_onSuccess)) + { + ThrowMsg(Commons::InvalidArgumentException, + "success callback is not a function"); + } + } else { + //LogWarning("onSuccessCallback is NULL and is not registred"); + } + if (NULL != onError && + (!acceptJSNullAsOnError || !JSValueIsNull(context, onError))) + { + l_onError = JSValueToObject(context, onError, NULL); + if (!l_onError || + !JSObjectIsFunction(context, l_onError)) + { + ThrowMsg(Commons::InvalidArgumentException, + "error callback is not a function"); + } + } else { + //LogWarning("onErrorCallback is NULL and is not registred"); + } + return JSCallbackManagerPtr(new JSCallbackManager(context, l_onSuccess, + l_onError)); +} + +JSCallbackManager::JSCallbackManager(JSContextRef context, + JSObjectRef onSuccess, + JSObjectRef onError) : + m_onSuccess(NULL), + m_onError(NULL), + m_context(context), + m_object(NULL) +{ + setOnSuccess(onSuccess); + setOnError(onError); +} + +JSCallbackManager::~JSCallbackManager() +{ + if (m_onSuccess) { + JSValueUnprotect(m_context, m_onSuccess); + } + + if (m_onError) { + JSValueUnprotect(m_context, m_onError); + } + + if (m_object) { + JSValueUnprotect(m_context, m_object); + } +} + +void JSCallbackManager::setOnSuccess(JSValueRef onSuccess) +{ + if (m_onSuccess != NULL) { + JSValueUnprotect(m_context, m_onSuccess); + } + + if (onSuccess) { + m_onSuccess = JSValueToObject(m_context, onSuccess, NULL); + } else { + m_onSuccess = NULL; + } + + if (m_onSuccess != NULL) { + JSValueProtect(m_context, m_onSuccess); + } +} + +JSValueRef JSCallbackManager::getOnSuccess() const +{ + return m_onSuccess; +} + +void JSCallbackManager::setOnError(JSValueRef onError) +{ + if (m_onError != NULL) { + JSValueUnprotect(m_context, m_onError); + } + + if (onError) { + m_onError = JSValueToObject(m_context, onError, NULL); + } else { + m_onError = NULL; + } + + if (m_onError != NULL) { + JSValueProtect(m_context, m_onError); + } +} + +JSValueRef JSCallbackManager::getOnError() const +{ + return m_onError; +} + +void JSCallbackManager::setObject(JSObjectRef object) +{ + if (m_object != NULL) { + JSValueUnprotect(m_context, m_object); + } + + m_object = object; + + if (m_object != NULL) { + JSValueProtect(m_context, m_object); + } +} + +JSObjectRef JSCallbackManager::getObject() const +{ + return m_object; +} + +void JSCallbackManager::setContext(JSContextRef context) +{ + m_context = context; +} + +void JSCallbackManager::callOnSuccess() +{ + if (m_onSuccess == NULL) { + //LogDebug("Success callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onSuccess, NULL, 0); +} + +void JSCallbackManager::callOnSuccess(JSValueRef obj) +{ + if (m_onSuccess == NULL) { + //LogDebug("Success callback is not set"); + return; + } + JSValueRef objParam[1] = { obj }; + makeCallback(m_context, NULL, m_onSuccess, objParam, 1); +} + +void JSCallbackManager::callOnSuccess(JSValueRef obj[], + int paramCount) +{ + if (m_onSuccess == NULL) { + //LogDebug("Success callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onSuccess, obj, paramCount); +} + +void JSCallbackManager::callOnError() +{ + if (m_onError == NULL) { + //LogDebug("Error callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onError, NULL, 0); +} + +void JSCallbackManager::callOnError(JSValueRef obj) +{ + if (m_onError == NULL) { + //LogDebug("Error callback is not set"); + return; + } + JSValueRef objParam[1] = { obj }; + makeCallback(m_context, NULL, m_onError, objParam, 1); +} + +void JSCallbackManager::callOnError(JSValueRef obj[], + int paramCount) +{ + if (m_onError == NULL) { + //LogDebug("Error callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onError, obj, paramCount); +} + +void JSCallbackManager::makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + JSValueRef argv[], + unsigned argc) +{ + if (callback == NULL) { + //LogError("callback is NULL"); + return; + } + + if (JSObjectIsFunction(context, callback)) { + JSValueRef exception = NULL; + + if (argc == 0) { + JSObjectCallAsFunction(context, callback, object, 0, NULL, &exception); + } else { + JSObjectCallAsFunction(context, callback, object, argc, argv, &exception); + } + + if (exception) { + WKBundleReportException(context, exception); + } + } +} +} +} diff --git a/src_wearable/CommonsJavaScript/JSCallbackManager.h b/src_wearable/CommonsJavaScript/JSCallbackManager.h new file mode 100644 index 0000000..6331eb1 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSCallbackManager.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file JSCallbackManager.h + * @author Lukasz Marek (l.marel@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ + + +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSCallbackManager; +typedef DPL::SharedPtr JSCallbackManagerPtr; + +class JSCallbackManager : public WrtDeviceApis::Commons::IEventPrivateData +{ + private: + JSCallbackManager() + {} + + /** + * Used to create JSCallbackManagerPtr object by factory method + * createObject + */ + JSCallbackManager(JSContextRef context, + JSObjectRef onSuccess, + JSObjectRef onError); + + public: + + //JSCallbackManager( JSContextRef context, JSValueRef onSuccess, JSValueRef + // onError ); + + /** + * Create JSCallbackManagerPtr object witch checking callback parameters + * if callbacks are NULL it was programmer intention to not use callback and + * no exception will be rised + * if callbacks are some object but not a function it will rise exception + * @param[in] context - global context + * @param[in] onSuccess - success callback (may be NULL if not needed) + * @param[in] onError - error callback (may be NULL if not needed) + * @param[in] acceptJSNullAsOnSuccess - converts JSNull on onSuccess to NULL + * when true + * @param[in] acceptJSNullAsOnError - converts JSNull on onError to NULL + * when true + * @throw Commons::InvalidArgumentException - if callback is not null and is + * not a js function + */ + static JSCallbackManagerPtr createObject( + JSContextRef context, + JSValueRef onSuccess = NULL, + JSValueRef onError = NULL, + bool acceptJSNullAsOnSuccess = false, + bool acceptJSNullAsOnError = false); + + virtual ~JSCallbackManager(); + + void setContext(JSContextRef context); + + JSContextRef getContext() const + { + return m_context; + } + + void setOnSuccess(JSValueRef onSuccess); + JSValueRef getOnSuccess() const; + void setOnError(JSValueRef onError); + JSValueRef getOnError() const; + void setObject(JSObjectRef object); + JSObjectRef getObject() const; + + void callOnSuccess(); + void callOnSuccess(JSValueRef obj); + void callOnSuccess(JSValueRef obj[], int paramCount); + + void callOnError(); + void callOnError(JSValueRef obj); + void callOnError(JSValueRef obj[], int paramCount); + + private: + void makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + JSValueRef argv[], + unsigned argc); + + JSObjectRef m_onSuccess; + JSObjectRef m_onError; + JSContextRef m_context; + JSObjectRef m_object; +}; + +bool isCallback(JSContextRef ctx, + JSValueRef value, + JSValueRef* exception); +} +} + +#endif // WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ diff --git a/src_wearable/CommonsJavaScript/JSDOMException.cpp b/src_wearable/CommonsJavaScript/JSDOMException.cpp new file mode 100644 index 0000000..ffee065 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSDOMException.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "JSDOMException.h" + +#include + +#include "Converter.h" + +namespace { +const char* PLUGIN_NAME = "DOMException"; +const char* PROPERTY_CODE = "code"; +const char* PROPERTY_MESSAGE = "message"; + +struct Error +{ + const char* name; + const unsigned short value; +}; +// This array CAN'T be left empty! +const Error PROPERTY_ERROR[] = { + { "UNKNOWN_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::UNKNOWN_ERR }, + { "INDEX_SIZE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INDEX_SIZE_ERR }, + { "DOMSTRING_SIZE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::DOMSTRING_SIZE_ERR }, + { "HIERARCHY_REQUEST_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + HIERARCHY_REQUEST_ERR }, + { "WRONG_DOCUMENT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::WRONG_DOCUMENT_ERR }, + { "INVALID_CHARACTER_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INVALID_CHARACTER_ERR }, + { "NO_DATA_ALLOWED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + NO_DATA_ALLOWED_ERR }, + { "NO_MODIFICATION_ALLOWED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + NO_MODIFICATION_ALLOWED_ERR }, + { "NOT_FOUND_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NOT_FOUND_ERR }, + { "NOT_SUPPORTED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NOT_SUPPORTED_ERR }, + { "INUSE_ATTRIBUTE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INUSE_ATTRIBUTE_ERR }, + { "INVALID_STATE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_STATE_ERR }, + { "SYNTAX_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::SYNTAX_ERR }, + { "INVALID_MODIFICATION_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INVALID_MODIFICATION_ERR }, + { "NAMESPACE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NAMESPACE_ERR }, + { "INVALID_ACCESS_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_ACCESS_ERR }, + { "VALIDATION_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::VALIDATION_ERR }, + { "TYPE_MISMATCH_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::TYPE_MISMATCH_ERR }, + { "SECURITY_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::SECURITY_ERR }, + { "NETWORK_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NETWORK_ERR }, + { "ABORT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::ABORT_ERR }, + { "TIMEOUT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::TIMEOUT_ERR }, + { "INVALID_VALUES_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_VALUES_ERR }, + { "IO_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::IO_ERR }, + { "QUOTA_EXCEEDED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::QUOTA_EXCEEDED_ERR } +}; +} // namespace + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +JSClassRef JSDOMException::m_classRef = NULL; + +JSClassDefinition JSDOMException::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + NULL, //__function, + initialize, + finalize, + hasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSDOMException::m_properties[] = { + { PROPERTY_CODE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MESSAGE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSDOMException::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSDOMException::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSDOMException::initialize(JSContextRef /*context*/, + JSObjectRef /*object*/) +{} + +void JSDOMException::finalize(JSObjectRef object) +{ + PrivateObject* privateObject = + static_cast(JSObjectGetPrivate(object)); + if (privateObject) { + JSObjectSetPrivate(object, NULL); + delete privateObject; + } +} + +bool JSDOMException::hasProperty(JSContextRef /*context*/, + JSObjectRef /*object*/, + JSStringRef propertyName) +{ + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_ERROR[i].name)) + { + return true; + } + } + return false; +} + +JSValueRef JSDOMException::getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + PrivateObject* privateObject = + static_cast(JSObjectGetPrivate(object)); + if (!privateObject) { + LogError("Private object is not set."); + return JSValueMakeUndefined(context); + } + + Converter converter(context); + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_CODE)) { + return converter.toJSValueRef(privateObject->getObject()->getCode()); + } else if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_MESSAGE)) + { + return converter.toJSValueRef( + privateObject->getObject()->getMessage()); + } + } catch (const Commons::ConversionException& ex) { + LogError("Exception: " << ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSDOMException::getProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + Converter converter(context); + try { + std::string prop = converter.toString(propertyName); + + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (prop == PROPERTY_ERROR[i].name) { + return converter.toJSValueRef(PROPERTY_ERROR[i].value); + } + } + } catch (const Commons::ConversionException& ex) { + LogError("Exception: " << ex.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +void JSDOMException::getPropertyNames( + JSContextRef /*context*/, + JSObjectRef /*object*/, + JSPropertyNameAccumulatorRef accumulator) +{ + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + JSPropertyNameAccumulatorAddName(accumulator, + JSStringCreateWithUTF8CString( + PROPERTY_ERROR[i].name)); + } +} + +bool JSDOMException::hasInstance(JSContextRef context, + JSObjectRef /*constructor*/, + JSValueRef possibleInstance, + JSValueRef* /*exception*/) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src_wearable/CommonsJavaScript/JSDOMException.h b/src_wearable/CommonsJavaScript/JSDOMException.h new file mode 100644 index 0000000..dcea1e4 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSDOMException.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_DOM_EXCEPTION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_DOM_EXCEPTION_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSDOMException +{ + public: + typedef PrivateObjectT::Type PrivateObject; + + public: + static const unsigned short UNKNOWN_ERR = 0; + static const unsigned short INDEX_SIZE_ERR = 1; + static const unsigned short DOMSTRING_SIZE_ERR = 2; + static const unsigned short HIERARCHY_REQUEST_ERR = 3; + static const unsigned short WRONG_DOCUMENT_ERR = 4; + static const unsigned short INVALID_CHARACTER_ERR = 5; + static const unsigned short NO_DATA_ALLOWED_ERR = 6; + static const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7; + static const unsigned short NOT_FOUND_ERR = 8; + static const unsigned short NOT_SUPPORTED_ERR = 9; + static const unsigned short INUSE_ATTRIBUTE_ERR = 10; + static const unsigned short INVALID_STATE_ERR = 11; + static const unsigned short SYNTAX_ERR = 12; + static const unsigned short INVALID_MODIFICATION_ERR = 13; + static const unsigned short NAMESPACE_ERR = 14; + static const unsigned short INVALID_ACCESS_ERR = 15; + static const unsigned short VALIDATION_ERR = 16; + static const unsigned short TYPE_MISMATCH_ERR = 17; + static const unsigned short SECURITY_ERR = 18; + static const unsigned short NETWORK_ERR = 19; + static const unsigned short ABORT_ERR = 20; + static const unsigned short TIMEOUT_ERR = 21; + static const unsigned short INVALID_VALUES_ERR = 22; + static const unsigned short IO_ERR = 100; + + //TODO INVALID_VALUES_ERR has the same error code ?? + static const unsigned short QUOTA_EXCEEDED_ERR = 22; + + public: + static JSClassRef getClassRef(); + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static void getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef accumulator); + + /** + * The callback invoked when an object is used as the target of an + * 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + static JSClassRef m_classRef; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // + diff --git a/src_wearable/CommonsJavaScript/JSDOMExceptionFactory.cpp b/src_wearable/CommonsJavaScript/JSDOMExceptionFactory.cpp new file mode 100644 index 0000000..10bddd4 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSDOMExceptionFactory.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "JSDOMExceptionFactory.h" + +#include +#include + +#include "JSUtils.h" +#include "DOMExceptionData.h" +#include "JSDOMException.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +#define DEFINE_JS_EXCEPTION_FACTORY(Class, Code) \ + JSDOMExceptionFactory JSDOMExceptionFactory::Class(Code) + +DEFINE_JS_EXCEPTION_FACTORY(UnknownException, JSDOMException::UNKNOWN_ERR); +DEFINE_JS_EXCEPTION_FACTORY(IndexSizeException, JSDOMException::INDEX_SIZE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(DomstringSizeException, + JSDOMException::DOMSTRING_SIZE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(HierarchyRequestException, + JSDOMException::HIERARCHY_REQUEST_ERR); +DEFINE_JS_EXCEPTION_FACTORY(WrongDocumentException, + JSDOMException::WRONG_DOCUMENT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidCharacterException, + JSDOMException::INVALID_CHARACTER_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NoDataAllowedException, + JSDOMException::NO_DATA_ALLOWED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NoModificationAllowedException, + JSDOMException::NO_MODIFICATION_ALLOWED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NotFoundException, JSDOMException::NOT_FOUND_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NotSupportedException, + JSDOMException::NOT_SUPPORTED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InuseAttributeException, + JSDOMException::INUSE_ATTRIBUTE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidStateException, + JSDOMException::INVALID_STATE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(SyntaxException, JSDOMException::SYNTAX_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidModificationException, + JSDOMException::INVALID_MODIFICATION_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NamespaceException, JSDOMException::NAMESPACE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidAccessException, + JSDOMException::INVALID_ACCESS_ERR); +DEFINE_JS_EXCEPTION_FACTORY(ValidationException, JSDOMException::VALIDATION_ERR); +DEFINE_JS_EXCEPTION_FACTORY(TypeMismatchException, + JSDOMException::TYPE_MISMATCH_ERR); +DEFINE_JS_EXCEPTION_FACTORY(SecurityException, JSDOMException::SECURITY_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NetworkException, JSDOMException::NETWORK_ERR); +DEFINE_JS_EXCEPTION_FACTORY(AbortException, JSDOMException::ABORT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(TimeoutException, JSDOMException::TIMEOUT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidValuesException, + JSDOMException::INVALID_VALUES_ERR); +DEFINE_JS_EXCEPTION_FACTORY(IOException, JSDOMException::IO_ERR); +DEFINE_JS_EXCEPTION_FACTORY(QuotaExceededException, + JSDOMException::QUOTA_EXCEEDED_ERR); + +JSDOMExceptionFactory::JSDOMExceptionFactory(int code) : m_code(code) +{} + +JSValueRef JSDOMExceptionFactory::make(JSContextRef context, + JSValueRef* exception, + const std::string& message) +{ + AssertMsg(exception, "Exception object can't be NULL."); + JSDOMException::PrivateObject::ObjectType data(new DOMExceptionData(m_code, + message)); + *exception = JSUtils::makeObject(context, + JSDOMException::getClassRef(), + data); + return JSValueMakeUndefined(context); +} + +JSObjectRef JSDOMExceptionFactory::make(JSContextRef context, + const std::string& message) +{ + JSDOMException::PrivateObject::ObjectType data(new DOMExceptionData(m_code, + message)); + return JSUtils::makeObject(context, + JSDOMException::getClassRef(), data); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_wearable/CommonsJavaScript/JSDOMExceptionFactory.h b/src_wearable/CommonsJavaScript/JSDOMExceptionFactory.h new file mode 100644 index 0000000..2bf8329 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSDOMExceptionFactory.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRT_DOM_EXCEPTION_FACTORY_H_ +#define WRT_DOM_EXCEPTION_FACTORY_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +#define DECLARE_JS_EXCEPTION_FACTORY(Class) static JSDOMExceptionFactory Class + +class JSDOMExceptionFactory : public DPL::Noncopyable +{ + public: + DECLARE_JS_EXCEPTION_FACTORY(UnknownException); + DECLARE_JS_EXCEPTION_FACTORY(IndexSizeException); + DECLARE_JS_EXCEPTION_FACTORY(DomstringSizeException); + DECLARE_JS_EXCEPTION_FACTORY(HierarchyRequestException); + DECLARE_JS_EXCEPTION_FACTORY(WrongDocumentException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidCharacterException); + DECLARE_JS_EXCEPTION_FACTORY(NoDataAllowedException); + DECLARE_JS_EXCEPTION_FACTORY(NoModificationAllowedException); + DECLARE_JS_EXCEPTION_FACTORY(NotFoundException); + DECLARE_JS_EXCEPTION_FACTORY(NotSupportedException); + DECLARE_JS_EXCEPTION_FACTORY(InuseAttributeException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidStateException); + DECLARE_JS_EXCEPTION_FACTORY(SyntaxException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidModificationException); + DECLARE_JS_EXCEPTION_FACTORY(NamespaceException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidAccessException); + DECLARE_JS_EXCEPTION_FACTORY(ValidationException); + DECLARE_JS_EXCEPTION_FACTORY(TypeMismatchException); + DECLARE_JS_EXCEPTION_FACTORY(SecurityException); + DECLARE_JS_EXCEPTION_FACTORY(NetworkException); + DECLARE_JS_EXCEPTION_FACTORY(AbortException); + DECLARE_JS_EXCEPTION_FACTORY(TimeoutException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidValuesException); + DECLARE_JS_EXCEPTION_FACTORY(IOException); + DECLARE_JS_EXCEPTION_FACTORY(QuotaExceededException); + + public: + explicit JSDOMExceptionFactory(int code); + + /** + * Creates exception object. + * @param context JS context of the exception. + * @param[out] exception Result object to which exception will be assigned. + * @return JS undefined value. + * @code + * JSValueRef JSClass::getProperty(JSContextRef context, + * JSObjectRef object, + * JSStringRef propertyName, + * JSValueRef* exception) + * { + * ... + * return JSExceptionFactory::InvalidArgumentException.make(context, + * exception); + * ... + * } + * @endcode + */ + JSValueRef make(JSContextRef context, + JSValueRef* exception, + const std::string& message = std::string()); + + /** + * Creates exception object. + * @param context JS context of the exception. + * @return JS exception object. + * @code + * JSObjectRef jsError = + * JSExceptionFactory::InvalidArgumentException.make(context); + * @endcode + */ + JSObjectRef make(JSContextRef context, + const std::string& message = std::string()); + + private: + int m_code; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // diff --git a/src_wearable/CommonsJavaScript/JSPendingOperation.cpp b/src_wearable/CommonsJavaScript/JSPendingOperation.cpp new file mode 100644 index 0000000..1891361 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSPendingOperation.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file JSPendingOperation.cpp + * @author Pete Cole (peter.cole@partner.samsung.com) + * @version 0.1 + * 0.2 k.majewski@samsung.com + * @brief Implementation of the JSPendingOperation class + */ + +#include +#include +#include "JSPendingOperation.h" +#include "JSPendingOperationPrivateObject.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +namespace { +const char* PLUGIN_NAME = "PendingOperation"; +} + +JSClassRef JSPendingOperation::m_classRef = NULL; + +JSClassDefinition JSPendingOperation::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + NULL, + m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticFunction JSPendingOperation::m_functions[] = { + { "cancel", cancel, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSPendingOperation::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSPendingOperation::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSPendingOperation::finalize(JSObjectRef object) +{ + delete static_cast( + JSObjectGetPrivate(object)); +} + +JSValueRef JSPendingOperation::cancel(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + (void) object; + (void) argumentCount; + (void) arguments; + (void) exception; + LogDebug(__FUNCTION__); + IJSPendingOperationPrivateObject *priv = + static_cast( + JSObjectGetPrivate(thisObject)); + assert(NULL != priv); + bool cancelResult = priv->cancel(); + LogDebug("cancel result : " << cancelResult); + return JSValueMakeBoolean(context, cancelResult); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src_wearable/CommonsJavaScript/JSPendingOperation.h b/src_wearable/CommonsJavaScript/JSPendingOperation.h new file mode 100644 index 0000000..1a67d89 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSPendingOperation.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file JSPendingOperation.h + * @author Pete Cole (peter.cole@partner.samsung.com) + * @version 0.1 + * 0.2 k.majewski@samsung.com + * @brief Declaration of the JSPendingOperation class + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDINGOPERATION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDINGOPERATION_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +//typedef Commons::PrivateObjectT::Type +// PendingOperationPrivateObject; + +class JSPendingOperation +{ + public: + /* + * This initializes this JS class in the JS Engine. + */ + static 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); + + /** + * 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[]; + + static JSClassRef m_classRef; + + /** + * Cancel the pending operation, if it has yet not completed. + */ + static JSValueRef cancel(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // _JS_WAC_PENDINGOPERATION_H_ + diff --git a/src_wearable/CommonsJavaScript/JSPendingOperationPrivateObject.h b/src_wearable/CommonsJavaScript/JSPendingOperationPrivateObject.h new file mode 100644 index 0000000..3c9b43d --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSPendingOperationPrivateObject.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDING_OPERATION_PRIVATE_OBJECT_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDING_OPERATION_PRIVATE_OBJECT_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class IJSPendingOperationPrivateObject +{ + public: + explicit IJSPendingOperationPrivateObject( + const DPL::SharedPtr + &event) : + m_event(event) + { + assert(NULL != m_event.Get()); + } + + virtual bool cancel() + { + LogDebug("PendingOperation tries to cancel the request"); + return m_event->cancelRequest(); + } + + virtual ~IJSPendingOperationPrivateObject() + {} + + protected: + DPL::SharedPtr m_event; +}; + +/* + * This class implements private object for JavaScript PendingOperation + * with support to external cancel function. + * + * When the cancel() method is invoked on PendingOperation, + * the OnCancelEvent() method is invoked on user object + * with apropriate * arguments. + * It allows user to perform an additional action when PendingOperation + * is destroyed. + * + * The Object which want to handle OnCancelEvent have to inherit from + * Platform::IExternEventCanceler. + * + * The cancel's handler have to be passed as second argument + * */ +template +class IJSExtCancelPendingOperationPrivateObject : + public IJSPendingOperationPrivateObject +{ + public: + IJSExtCancelPendingOperationPrivateObject( + const DPL::SharedPtr< TemplateEvent> &event, + const DPL::SharedPtr< + Commons::IExternEventCanceler > & cancel) : + IJSPendingOperationPrivateObject( + DPL::StaticPointerCast(event)), + m_canceler(cancel) + { + assert(NULL != m_canceler); + } + + virtual bool cancel() + { + bool result = IJSPendingOperationPrivateObject::cancel(); + if (!result) { + LogDebug("Controller can not cancel event, trying platform cancel"); + } else { + return result; + } + + if (m_canceler) { + LogDebug("Calling extern cancel"); + m_canceler->OnCancelEvent( + DPL::StaticPointerCast(m_event)); + } + + return result; + } + + virtual ~IJSExtCancelPendingOperationPrivateObject() + {} + + protected: + DPL::SharedPtr< Commons::IExternEventCanceler > m_canceler; +}; +} +} +#endif /* _JS_WAC_PENDING_OPERATION_PRIVATE_OBJECT_H_ */ diff --git a/src_wearable/CommonsJavaScript/JSUtils.cpp b/src_wearable/CommonsJavaScript/JSUtils.cpp new file mode 100644 index 0000000..f4c9c95 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSUtils.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "Converter.h" +#include "ScopedJSStringRef.h" +#include "JSUtils.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +using namespace WrtDeviceApis::Commons; + +bool JSUtils::hasProperty(JSStaticValue* properties, + JSStringRef name) +{ + JSStaticValue* property = properties; + while (property->name) { + if (JSStringIsEqualToUTF8CString(name, property->name)) { + return true; + } + ++property; + } + return false; +} + +JSValueRef JSUtils::getJSProperty(JSContextRef context, + JSValueRef jsValue, + const std::string &name, + JSValueRef *exception) +{ + ScopedJSStringRef jsPropName(JSStringCreateWithUTF8CString(name.c_str())); + Converter converter(context); + JSObjectRef jsObject = converter.toJSObjectRef(jsValue); + if (JSObjectHasProperty(context, jsObject, jsPropName.get())) { + return JSObjectGetProperty(context, jsObject, + jsPropName.get(), exception); + } + return NULL; +} + +JSValueRef JSUtils::getJSProperty(JSContextRef context, + JSObjectRef object, + const std::string& name) +{ + Converter converter(context); + Try { + ScopedJSStringRef propName(converter.toJSStringRef(name)); + if (JSObjectHasProperty(context, object, propName.get())) { + JSValueRef result = JSObjectGetProperty(context, + object, + propName.get(), + NULL); + if (!JSValueIsUndefined(context, result)) { + return result; + } + } + } + Catch(ConversionException) {} + return NULL; +} + +JSValueRef JSUtils::getJSPropertyOrUndefined(JSContextRef context, + JSObjectRef object, + const std::string& name) +{ + Converter converter(context); + Try { + ScopedJSStringRef propName(converter.toJSStringRef(name)); + if (JSObjectHasProperty(context, object, propName.get())) { + return JSObjectGetProperty(context, object, propName.get(), NULL); + } + } + Catch(ConversionException) {} + return JSValueMakeUndefined(context); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_wearable/CommonsJavaScript/JSUtils.h b/src_wearable/CommonsJavaScript/JSUtils.h new file mode 100644 index 0000000..5d835a1 --- /dev/null +++ b/src_wearable/CommonsJavaScript/JSUtils.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_JSUTILS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_JSUTILS_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSUtils +{ + public: + static bool hasProperty(JSStaticValue* properties, + JSStringRef name); + + /** + * Gets a property from JSObject if exists + * @return JSValueRef if property exists, NULL if not + */ + static JSValueRef getJSProperty(JSContextRef context, + JSValueRef jsValue, + const std::string &name, + JSValueRef* exception = NULL); + + static JSValueRef getJSProperty(JSContextRef context, + JSObjectRef object, + const std::string& name); + + static JSValueRef getJSPropertyOrUndefined(JSContextRef context, + JSObjectRef object, + const std::string& name); + + template + static JSObjectRef makeObject(JSContextRef context, + JSClassRef classRef, + C data) + { + typedef typename PrivateObjectT::Type Private; + + Private* priv = new Private(context, data); + JSObjectRef object = JSObjectMake(context, classRef, priv); + if (!object) { + ThrowMsg(Commons::NullPointerException, + "Could not create JS object."); + } + + return object; + } + + static JSObjectRef makeObject(JSContextRef context, + JSClassRef classRef) + { + typedef PrivateObjectT::Type Private; + + Private* priv = new Private(context); + JSObjectRef object = JSObjectMake(context, classRef, priv); + if (!object) { + ThrowMsg(Commons::NullPointerException, + "Could not create JS object."); + } + + return object; + } +}; // JSUtils +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTPLUGINS_COMMONS_JSUTILS_H_ */ diff --git a/src_wearable/CommonsJavaScript/PrivateObject.h b/src_wearable/CommonsJavaScript/PrivateObject.h new file mode 100644 index 0000000..8bd816a --- /dev/null +++ b/src_wearable/CommonsJavaScript/PrivateObject.h @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_PRIVATEOBJECT_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_PRIVATEOBJECT_H_ + +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template +struct NoAcquire +{ + void acquire(T*) + {} + + protected: + ~NoAcquire() + {} +}; + +template +struct AcquireByProtect +{ + void acquire(T* object) + { + Assert(object && "Object passed to protect can't be NULL."); + JSValueProtect(object->getContext(), object->getObject()); + } + + protected: + ~AcquireByProtect() + {} +}; + +template +struct NoRelease +{ + void release(T* object) + { + (void)object; + } + + protected: + ~NoRelease() + {} +}; + +template +struct ReleaseByDelete +{ + void release(T* object) + { + delete object->getObject(); + } + + protected: + ~ReleaseByDelete() + {} +}; + +template +struct ReleaseByUnprotect +{ + void release(T* object) + { + Assert(object && "Object passed to unprotect can't be NULL."); + JSValueUnprotect(object->getContext(), object->getObject()); + } + + protected: + ~ReleaseByUnprotect() + {} +}; + +template +struct NoOwnership : protected NoAcquire, + protected NoRelease +{ + protected: + ~NoOwnership() + {} +}; + +template +struct OwnershipByAcquisition : protected NoAcquire, + protected ReleaseByDelete +{ + protected: + ~OwnershipByAcquisition() + {} +}; + +template +struct OwnershipByProtection : protected AcquireByProtect, + protected ReleaseByUnprotect +{ + protected: + ~OwnershipByProtection() + {} +}; + +template class OwnershipPolicy = OwnershipByAcquisition> +class PrivateObject : public DPL::Noncopyable, + protected OwnershipPolicy > +{ + public: + typedef PrivateClass ObjectType; + + public: + /** + * Creates storage object for JS private data. + * @param context JS (root/global) context. + * @param object Object to store. + * @throw NullPointerException When object is pointer and is set to NULL. + */ + PrivateObject(JSContextRef context, + const PrivateClass& object) : + m_context(context), + m_object(object) + { + Assert(NULL != m_context && "Context is NULL."); + Assert(!Commons::IsNull::value( + object) && "Object is NULL."); + this->acquire(this); + } + + /** + * Destroys instance of the object. + */ + virtual ~PrivateObject() + { + this->release(this); + } + + /** + * Gets stored JS context. + * @return JavaScript context. + */ + virtual JSContextRef getContext() const + { + return m_context; + } + + /** + * Gets stored object. + * @return Stored object. + */ + virtual PrivateClass getObject() const + { + return m_object; + } + + protected: + JSContextRef m_context; ///< JS context. + PrivateClass m_object; ///< Stored object. +}; + +/** + * Specialization for type void. + */ +template<> +class PrivateObject : private DPL::Noncopyable +{ + public: + /** + * Creates storage object for JS private data. + * @param context JS (root/global) context. + * @remarks Takes ownership over stored object. + */ + explicit PrivateObject(JSContextRef context) : m_context(context) + { + Assert(NULL != m_context && "Context is NULL."); + } + + /** + * Destroys instance of the object. + */ + virtual ~PrivateObject() + {} + + /** + * Gets stored JS context. + * @return JavaScript context. + */ + virtual JSContextRef getContext() const + { + return m_context; + } + + protected: + JSContextRef m_context; +}; + +template +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; + +template +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; + +template<> +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; + +template<> +struct PrivateObjectT +{ + typedef PrivateObject Type; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* PRIVATEOBJECT_H_ */ diff --git a/src_wearable/CommonsJavaScript/ScopedJSStringRef.cpp b/src_wearable/CommonsJavaScript/ScopedJSStringRef.cpp new file mode 100644 index 0000000..2f0c17f --- /dev/null +++ b/src_wearable/CommonsJavaScript/ScopedJSStringRef.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ScopedJSStringRef.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +ScopedJSStringRef::ScopedJSStringRef(JSStringRef ref) : m_ref(ref) +{} + +ScopedJSStringRef::~ScopedJSStringRef() +{ + if (m_ref != NULL) { + JSStringRelease(m_ref); + } +} + +JSStringRef ScopedJSStringRef::get() const +{ + return m_ref; +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_wearable/CommonsJavaScript/ScopedJSStringRef.h b/src_wearable/CommonsJavaScript/ScopedJSStringRef.h new file mode 100644 index 0000000..d18238a --- /dev/null +++ b/src_wearable/CommonsJavaScript/ScopedJSStringRef.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * Takes ownership over JSStringRef object to call JSSTringRelease on it + * when this object goes out of scope. + */ +class ScopedJSStringRef : private DPL::Noncopyable +{ + public: + /** + * Creates this class instance. + * @param ref JSStringRef to take ownership. + * @remarks Takes ownership. + */ + ScopedJSStringRef(JSStringRef ref); + + /** + * Destroys instance. + * @remarks Releases stored JSStringRef. + */ + ~ScopedJSStringRef(); + + /** + * Gets stored JSStringRef. + * @return JSStringRef object. + * @remarks Doesn't pass ownership to caller. + */ + JSStringRef get() const; + + private: + JSStringRef m_ref; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ */ diff --git a/src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp b/src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp new file mode 100644 index 0000000..87111fd --- /dev/null +++ b/src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "SecurityFunctionDeclaration.h" +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +AceSecurityStatus aceCheckAccessSimple( + WrtDeviceApis::Commons::AceFunction aceFunction) +{ + return aceCheckAccess2 >(aceFunction); +} +} +} diff --git a/src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.h b/src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.h new file mode 100644 index 0000000..8ad1987 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Security/SecurityFunctionDeclaration.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef _FUNCTION_DECLARATION_ +#define _FUNCTION_DECLARATION_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +enum class AceSecurityStatus +{ + AccessGranted, + AccessDenied, + PrivacyDenied, + InternalError +}; + +template +class DefaultArgsVerifier +{ + public: + void operator()(WrtDeviceApis::Commons::AceFunction& aceFunction, + Args && ... args) const + { + static_assert( + WrtDeviceApis::Commons::AlwaysFalse::value, + "Please provide a specialization for these argument types!"); + } +}; + +template <> +class DefaultArgsVerifier<> +{ + public: + void operator()(WrtDeviceApis::Commons::AceFunction& /*aceFunction*/) const + {} +}; + +template +AceSecurityStatus aceCheckAccess2( + WrtDeviceApis::Commons::AceFunction aceFunction, + Args && ... args) +{ + using namespace WrtDeviceApis::Commons; + + ArgumentsVerifier argsVerify; + argsVerify(aceFunction, args ...); + + WrtAccess::CheckAccessReturnType ret = + WrtAccessSingleton::Instance().checkAccessControl(aceFunction); + + if (ret == WrtAccess::CHECK_ACCESS_PRIVILEGE_DENIED) { + LogError("Function is not allowed to run - AccessDenied"); + return AceSecurityStatus::AccessDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_PRIVACY_DENIED) { + LogError("Function is not allowed to run - PrivacyDenied"); + return AceSecurityStatus::PrivacyDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_INTERNAL_ERROR) { + LogError("InternalError"); + return AceSecurityStatus::InternalError; + } + + LogDebug("Function accepted!"); + + return AceSecurityStatus::AccessGranted; +} + +//The simplest version +AceSecurityStatus aceCheckAccessSimple( + WrtDeviceApis::Commons::AceFunction aceFunction); +} +} + +#endif // _FUNCTION_DECLARARION_ diff --git a/src_wearable/CommonsJavaScript/Security/StaticDeclaration.h b/src_wearable/CommonsJavaScript/Security/StaticDeclaration.h new file mode 100644 index 0000000..c089d50 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Security/StaticDeclaration.h @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _WRTPLUGINS_COMMONS_SRC_COMMONS_STATICDECLARATIOS_H_ +#define _WRTPLUGINS_COMMONS_SRC_COMMONS_STATICDECLARATIOS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template +class StaticDeclarations : public DPL::Noncopyable +{ + struct FunctionTriplet { + const char* name; + std::vector devCaps; + std::vector features; + }; + + public: + + typedef typename std::map ParamsMap; + + typedef std::map > > DeviceCapsMaps; + + typedef std::map FunctionsMap; + + typedef std::map + AceFunctionsMap; + + typedef std::map > FeaturesMap; + + static const std::string getParamName(const ParamType& paramId) + { + auto it = m_params.find(paramId); + + Assert(it != m_params.end() && "No such paramId"); + + return it->second; + } + + /** + * Returns set of device capabilities WITHOUT params + * for given device capability id + * */ + static WrtDeviceApis::Commons::AceDeviceCapability + getDeviceCapabilityWithoutParams(const DeviceCapType& devCapsId) + { + WrtDeviceApis::Commons::AceDeviceCapability deviceCap; + auto it = m_deviceCaps.find(devCapsId); + + Assert(it != m_deviceCaps.end() && "No such device cap"); + + deviceCap.devCapName = it->second.first; + + return deviceCap; + } + + /** + * Returns set of device capabilities with set params + * for given device capability id + * */ + static WrtDeviceApis::Commons::AceDeviceCapability + getDeviceCapability(const DeviceCapType& devCapsId) + { + auto it = m_deviceCaps.find(devCapsId); + + Assert(it != m_deviceCaps.end() && "No such dev-cap found"); + + WrtDeviceApis::Commons::AceDeviceCapability deviceCap; + deviceCap.devCapName = it->second.first; + + FOREACH(paramIt, it->second.second) + { + WrtDeviceApis::Commons::AceDeviceCapParam param( + getParamName(*paramIt), + std::string()); + + deviceCap.devCapParams.push_back(param); + } + + return deviceCap; + } + + static void addDeviceCapabilty( + const DeviceCapType& devCapsId, + WrtDeviceApis::Commons::AceFunction& aceFunction) + { + aceFunction.deviceCapabilities.push_back( + getDeviceCapability(devCapsId)); + } + + /** + * Returns names of device-capabilities base on capability id + */ + static std::string getDevCapNameById(DeviceCapType devCapId) + { + auto it = m_deviceCaps.find(devCapId); + Assert(it != m_deviceCaps.end() && "No such devcapid found!"); + return it->second.first; + } + + /** + * Sets parameter value for given paramId + */ + static bool setParamValue(WrtDeviceApis::Commons::AceFunction& function, + ParamType paramId, + DeviceCapType devCapId, + const std::string& value) + { + //get name of the deviceCaps + std::string devCapName = getDevCapNameById(devCapId); + std::string paramName = getParamName(paramId); + + //search throw all the device capabilities + FOREACH(devCapIt, function.deviceCapabilities) { + if (devCapIt->devCapName == devCapName) { + //device capability has been found + //check params + FOREACH(devParamIt, devCapIt->devCapParams) { + if (devParamIt->name == paramName) { + devParamIt->value = value; + return true; + } + } + } + } + return false; + } + /** + * Return struct Commons::AceFunction with set function name + * + * To set device capabilities you may use setDeviceCap function + * To set param value function you may use setParamValue Function + * */ + static WrtDeviceApis::Commons::AceFunction getEmptyFunction( + const FunctionType& functionId) + { + WrtDeviceApis::Commons::AceFunction function; + auto it = m_functions.find(functionId); + Assert(it != m_functions.end() && "No such a function"); + function.name = it->second.first; + + return function; + } + + /** + * The most useful Function + * Return Commons::AceFunction with filled all required fields: + * name, device caps and proper param namespace + * + * To set param value function you may use setParamValue function + * */ + static WrtDeviceApis::Commons::AceFunction getSecurityFunction( + const FunctionType& functionId) + { + WrtDeviceApis::Commons::AceFunction function; + auto it = m_functions.find(functionId); + Assert(it != m_functions.end() && "No such function found!"); + + function.name = it->second.name; + + FOREACH(featIt, it->second.features) + function.features.push_back(std::string(*featIt)); + + FOREACH(devCapIt, it->second.devCaps) { + function.deviceCapabilities.push_back( + getDeviceCapability(*devCapIt)); + } + return function; + } + + /** + * To create static map + * */ + static void createStaticAceFunctions() + { + FOREACH(functionIt, m_functions) + { + m_aceFunctions[functionIt->first] = + getSecurityFunction(functionIt->first); + } + } + + static feature_mapping_t* getFeaturesToDevCapMapping() + { + feature_mapping_t* mapping = new feature_mapping_t; + + mapping->featuresCount = m_features.size(); + mapping->features = new feature_devcaps_t[mapping->featuresCount]; + + size_t i = 0; + + FOREACH(featureIt, m_features) + { + mapping->features[i].feature_name = + strndup(featureIt->first.c_str(), featureIt->first.size() + 1); + + mapping->features[i].devCaps.devCapsCount = + featureIt->second.size(); + + mapping->features[i].devCaps.deviceCaps = + new char*[mapping->features[i].devCaps.devCapsCount]; + + for (size_t j = 0; + j < mapping->features[i].devCaps.devCapsCount; + ++j) + { + std::string dc = getDevCapNameById(featureIt->second[j]); + + mapping->features[i].devCaps.deviceCaps[j] = + strndup(dc.c_str(), dc.size() + 1); + } + + ++i; + } + + return mapping; + } + + static const devcaps_t* devcapsGetter(pfeature_mapping_t feats, + const char* featureName) + { + Assert(featureName && "Trying to extract info about NULL api feature"); + + std::string feature(featureName); + + devcaps_t* ret = NULL; + + for (size_t i = 0; i < feats->featuresCount; ++i) { + Assert(feats->features && + feats->features[i].feature_name && + "NULL api feature in feature mapping"); + + std::string feat(feats->features[i].feature_name); + + if (feature == feat) { + ret = &(feats->features[i].devCaps); + break; + } + } + + return ret; + } + + static void featuresDeinitializer(feature_mapping_t* mapping) + { + if (mapping) { + if (mapping->features) { + for (size_t i = 0; i < mapping->featuresCount; ++i) { + free(mapping->features[i].feature_name); + + devcaps_t& dc = mapping->features[i].devCaps; + + if (dc.deviceCaps) { + for (size_t j = 0; j < dc.devCapsCount; ++j) { + free(dc.deviceCaps[j]); + } + + delete[] dc.deviceCaps; + } + } + delete[] mapping->features; + } + delete mapping; + } + } + + static void getMappingInterface(feature_mapping_interface_t *mapping) + { + if (mapping) { + mapping->featGetter = + StaticDeclarations::getFeaturesToDevCapMapping; + mapping->dcGetter = StaticDeclarations::devcapsGetter; + mapping->release = StaticDeclarations::featuresDeinitializer; + } + } + + private: + static ParamsMap m_params; + static DeviceCapsMaps m_deviceCaps; + static FunctionsMap m_functions; + static AceFunctionsMap m_aceFunctions; + + static FeaturesMap m_features; +}; +} +} + +#endif diff --git a/src_wearable/CommonsJavaScript/SecurityExceptions.h b/src_wearable/CommonsJavaScript/SecurityExceptions.h new file mode 100644 index 0000000..ffc111b --- /dev/null +++ b/src_wearable/CommonsJavaScript/SecurityExceptions.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ + +#include +#include "JSDOMExceptionFactory.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * synchronously checks access status and throws JS Security exception if + * necessary + */ +#define SYNC_ACCESS_STATUS_HANDLER(status, context, exception) \ + do { \ + switch (status) \ + { \ + case AceSecurityStatus::InternalError: \ + return JSDOMExceptionFactory::UnknownException.make( \ + context, exception); \ + break; \ + \ + case AceSecurityStatus::AccessDenied: \ + return JSDOMExceptionFactory::SecurityException.make( \ + context, exception); \ + break; \ + \ + default: \ + break; \ + } \ + } while (0) + +/** + * checks access status and returns an error through JSCallbackManager if + * necessary + */ +#define ASYNC_CBM_ACCESS_STATUS_HANDLER(status, context, cbm) \ + do { \ + switch (status) \ + { \ + case AceSecurityStatus::InternalError: \ + cbm->callOnError(JSDOMExceptionFactory::UnknownException.make( \ + context)); \ + return JSValueMakeNull(context); \ + \ + case AceSecurityStatus::AccessDenied: \ + cbm->callOnError(JSDOMExceptionFactory::SecurityException.make( \ + context)); \ + return JSValueMakeNull(context); \ + \ + default: \ + break; \ + } \ + } while (0) +} +} +#endif /*WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ */ + diff --git a/src_wearable/CommonsJavaScript/SupportPendingOperation.h b/src_wearable/CommonsJavaScript/SupportPendingOperation.h new file mode 100644 index 0000000..cf8484b --- /dev/null +++ b/src_wearable/CommonsJavaScript/SupportPendingOperation.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_SUPPORT_PENDING_OPERATION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_SUPPORT_PENDING_OPERATION_H_ + +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template +class SupportPendingOperation +{ + public: + virtual T getPendingOperation() const + { + return *m_operation; + } + + virtual void setPendingOperation(const T& operation) + { + m_operation = operation; + } + + bool checkPendingOperation() const + { + return !m_operation.IsNull(); + } + + virtual ~SupportPendingOperation(){} + + protected: + boost::optional m_operation; +}; +} +} + +#endif diff --git a/src_wearable/CommonsJavaScript/Utils.h b/src_wearable/CommonsJavaScript/Utils.h new file mode 100644 index 0000000..d8b8f95 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Utils.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_UTILS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_UTILS_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * Creates pending operation object. + * @param context Global context. + * @param event Event or other object enclosed in shared ptr and convertible + * to @see WrtDeviceApis::Commons::IEventController. + * @return Pending operation object. + */ +template +JSObjectRef makePendingOperation(JSContextRef context, + const DPL::SharedPtr& event) +{ + Commons::IEventControllerPtr eventController = + DPL::StaticPointerCast(event); + IJSPendingOperationPrivateObject* pendingOperation = + new IJSPendingOperationPrivateObject(eventController); + return JSObjectMake(context, + JSPendingOperation::getClassRef(), pendingOperation); +} + +template +JSObjectRef makeExtCancelSupportedPendingOperation( + JSContextRef context, + const DPL::SharedPtr& event, + const DPL::SharedPtr >& + cancel) +{ + IJSPendingOperationPrivateObject* pendingOperation = + new IJSExtCancelPendingOperationPrivateObject(event, cancel); + + return JSObjectMake(context, + JSPendingOperation::getClassRef(), + pendingOperation); +} +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONSJAVASCRIPT_UTILS_H_ diff --git a/src_wearable/CommonsJavaScript/Validator.cpp b/src_wearable/CommonsJavaScript/Validator.cpp new file mode 100644 index 0000000..fe30b08 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Validator.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "Validator.h" +#include +#include +#include "ScopedJSStringRef.h" +#include "Converter.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +Validator::Validator(JSContextRef context, + JSValueRef* exception) : + m_context(context), + m_exception(exception) +{ + AssertMsg(NULL != m_context, "Context cannot be NULL."); +} + +Validator::~Validator() +{} + +bool Validator::isDate(const JSValueRef& arg) +{ + if (JSValueIsNull(m_context, + arg) || + JSValueIsUndefined(m_context, + arg) || !JSValueIsObject(m_context, arg)) + { + return false; + } + Converter converter(m_context); + Try + { + converter.toDateTm(arg); + } + Catch(Commons::ConversionException) + { + return false; + } + return true; +} + +bool +Validator::isCallback(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSObjectIsFunction(m_context, converter.toJSObjectRef(arg)); +} + +bool +Validator::checkArrayKeys(const std::vector &allowed, + JSValueRef argument) +{ + if (argument == NULL) { + return true; + } + if (!JSValueIsObject(m_context, argument)) { + return false; + } + JSObjectRef jsOptions = JSValueToObject(m_context, argument, NULL); + if (jsOptions == NULL) { + return false; + } + JSPropertyNameArrayRef jsProps = JSObjectCopyPropertyNames(m_context, + jsOptions); + if (jsProps == NULL) { + // No properties found; and empty array. + return true; + } + size_t nCount = JSPropertyNameArrayGetCount(jsProps); + bool found; + + std::list allowedJS; + for (size_t j = 0; j < allowed.size(); j++) { + allowedJS.push_back(JSStringCreateWithUTF8CString(allowed[j].c_str())); + } + + for (size_t i = 0; i < nCount; i++) { + found = false; + for (std::list::const_iterator it = allowedJS.begin(); + it != allowedJS.end(); + ++it) + { + if (JSStringIsEqual(*it, + JSPropertyNameArrayGetNameAtIndex(jsProps, + i))) + { + found = true; + break; + } + } + if (!found) { + for (size_t j = 0; j < allowed.size(); j++) { + JSStringRelease(allowedJS.front()); + allowedJS.pop_front(); + } + JSPropertyNameArrayRelease(jsProps); + return false; + } + } + + for (size_t j = 0; j < allowed.size(); j++) { + JSStringRelease(allowedJS.front()); + allowedJS.pop_front(); + } + JSPropertyNameArrayRelease(jsProps); + return true; +} + +bool Validator::isNullOrUndefined(const JSValueRef& arg) +{ + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg)); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src_wearable/CommonsJavaScript/Validator.h b/src_wearable/CommonsJavaScript/Validator.h new file mode 100644 index 0000000..6a89550 --- /dev/null +++ b/src_wearable/CommonsJavaScript/Validator.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_VALIDATOR_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_VALIDATOR_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class Validator : private DPL::Noncopyable +{ + public: + explicit Validator(JSContextRef context, + JSValueRef* exception = NULL); + virtual ~Validator(); + + /** + * Checks if arg is a Date. + * @param arg JSValueRef to check. + * @return true when object is a date, false otherwise + */ + bool isDate(const JSValueRef& arg); + + /** + * Checks if arg is a callback function. + * @param arg JSValueRef to check. + * @return true when object is a callback function, false otherwise + */ + bool isCallback(const JSValueRef& arg); + + /** + * Checks if arg have allowed properties. + * @param allowed allowed property names. + * @param arg JSValueRef to check. + * @return true when object's properties are subset of allowed + */ + bool checkArrayKeys(const std::vector &allowed, + JSValueRef argument); + + bool isNullOrUndefined(const JSValueRef& arg); + + protected: + JSContextRef m_context; + JSValueRef* m_exception; +}; + +template +class ValidatorFactory : private DPL::Noncopyable +{ + public: + /** + * Validator type which deletes itself when gets out of scope. + */ + typedef DPL::SharedPtr ValidatorType; + + public: + /** + * Gets converter object. + * @param context JavaScript context the conversion will be performed in. + * @param[out] exception JavaScript value for storing exception. + * @return Converter object. + */ + static ValidatorType getValidator(JSContextRef context, + JSValueRef* exception = NULL) + { + C* convert = new C(context, exception); + return ValidatorType(convert); + } + + private: + ValidatorFactory(); +}; + +typedef ValidatorFactory BasicValidatorFactory; +typedef BasicValidatorFactory::ValidatorType BasicValidator; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* _VALIDATOR_H_ */ diff --git a/src_wearable/DESCRIPTION b/src_wearable/DESCRIPTION new file mode 100644 index 0000000..bc2b1d7 --- /dev/null +++ b/src_wearable/DESCRIPTION @@ -0,0 +1 @@ +Main source folder diff --git a/src_wearable/dispatch-event/CMakeLists.txt b/src_wearable/dispatch-event/CMakeLists.txt new file mode 100644 index 0000000..3ba4072 --- /dev/null +++ b/src_wearable/dispatch-event/CMakeLists.txt @@ -0,0 +1,59 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Tae-Jeong Lee (taejeong.lee@samsung.com) +# @version 1.0 +# + +pkg_search_module(webkit2 REQUIRED ewebkit2) +pkg_search_module(dpl REQUIRED dpl-efl) + +SET(TARGET_NAME wrt-dispatch-event) + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/dispatch_event_support.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${webkit2_INCLUDE_DIRS} + ${dpl_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${webkit2_LIBRARIES} + ${dpl_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} + DESTINATION ${DESTINATION_LIB_PREFIX} + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES dispatch_event_support.h DESTINATION include/wrt-dispatch-event) \ No newline at end of file diff --git a/src_wearable/dispatch-event/dispatch_event_support.cpp b/src_wearable/dispatch-event/dispatch_event_support.cpp new file mode 100644 index 0000000..b07500d --- /dev/null +++ b/src_wearable/dispatch-event/dispatch_event_support.cpp @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file dispatch_event_support.cpp + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _DISPATCH_EVENT_SUPPORT_CPP_ +#define _DISPATCH_EVENT_SUPPORT_CPP_ + +#include "dispatch_event_support.h" + +namespace DispatchEventSupport { + +static std::string getExceptionString(JSContextRef context, JSValueRef exception) +{ + if (exception) + { + JSStringRef jsString = JSValueToStringCopy(context, exception, NULL); + size_t bufSize = JSStringGetMaximumUTF8CStringSize(jsString); + + char* buf = new char[bufSize]; + JSStringGetUTF8CString(jsString, buf, bufSize); + JSStringRelease(jsString); + + std::string ret = buf; + delete[] buf; + + return ret; + } + else + { + return "NULL"; + } +} + +void dispatchAppServiceEvent(JSContextRef context, const float scale, const std::string bundle) +{ + LogDebug("DispatchTizenServiceEvent(" << context << ", " << scale << ", " << bundle << ")"); + + if (context != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"appservice\", true, true);\n" + << "__event.scale = " << scale << ";\n" + << "__event.__bundle = \"" << bundle << "\";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + LogDebug("JSEvaluateScript() - ret:" << ret << ", exception:" << exception << " (" << getExceptionString(context, exception) << ")"); + } +} + +void dispatchSoftKeyboardChangeEvent(JSContextRef context, const std::string state, const int width, const int height) +{ + LogDebug("dispatchSoftKeyboardChangeEvent(" << context << ", " << state << ", " << width << ", " << height << ")"); + + if (context != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"softkeyboardchange\", true, true);\n" + << "__event.state = \"" << state << "\";\n" + << "__event.width = " << width << ";\n" + << "__event.height = " << height << ";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + LogDebug("JSEvaluateScript() - ret:" << ret << ", exception:" << exception << " (" << getExceptionString(context, exception) << ")"); + } +} + +void dispatchStorageEvent(JSContextRef context, + const DPL::OptionalStdString& key, + const DPL::OptionalStdString& oldValue, + const DPL::OptionalStdString& newValue, + const std::string& url) +{ + LogDebug("dispatchStorageEvent(" << + context << ", " << + (!(key) ? "null" : *key) << ", " << + (!(oldValue) ? "null" : *oldValue) << ", " << + (!(newValue) ? "null" : *newValue) << ", " << + url << ")"); + + if (context != NULL) + { + std::stringstream script; + + auto toJSValue = + [](const DPL::OptionalStdString& value) -> std::string + { + return ((!value) ? "null" : "\"" + *value + "\""); + }; + + script << "var __event = document.createEvent(\"CustomEvent\");" + << "__event.initCustomEvent(\"storage\", true, true);" + << "__event.key = " << toJSValue(key) << ";" + << "__event.oldValue = " << toJSValue(oldValue) << ";" + << "__event.newValue = " << toJSValue(newValue) << ";" + << "__event.url = \"" << url << "\";" + << "__event.storageArea = widget.preferences;" + << "document.dispatchEvent(__event);" + << "for (var i=0; i < window.frames.length; i++)" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + + // just for debugging + // LogDebug("script :\n" << script.str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + LogDebug("JSEvaluateScript() - ret:" << ret << ", exception:" << exception << " (" << getExceptionString(context, exception) << ")"); + } +} + +void dispatchHwKeyEvent(Evas_Object* ewkView, const std::string key) +{ + LogDebug("dispatchHwKeyEvent(" << ewkView << ", " << key << ")"); + + if (ewkView != NULL && !key.empty()) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"tizenhwkey\", true, true);\n" + << "__event.keyName = \"" << key << "\";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + if (ewk_view_script_execute(ewkView, script.str().c_str(), NULL, NULL) != EINA_TRUE) + { + LogWarning("ewk_view_script_execute returned FALSE!"); + } + } +} + +void dispatchAppControlEvent(Evas_Object* ewkView) +{ + LogDebug("dispatchAppControlEvent(" << ewkView << ")"); + + if (ewkView != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"appcontrol\", true, true);\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // LogDebug("script :\n" << script.str()); + + if (ewk_view_script_execute(ewkView, script.str().c_str(), NULL, NULL) != EINA_TRUE) + { + LogWarning("ewk_view_script_execute returned FALSE!"); + } + } +} + +} +#endif //_DISPATCH_EVENT_SUPPORT_CPP_ diff --git a/src_wearable/dispatch-event/dispatch_event_support.h b/src_wearable/dispatch-event/dispatch_event_support.h new file mode 100644 index 0000000..4d8805d --- /dev/null +++ b/src_wearable/dispatch-event/dispatch_event_support.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file dispatch_event_support.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _DISPATCH_EVENT_SUPPORT_H_ +#define _DISPATCH_EVENT_SUPPORT_H_ + +#include +#include +#include +#include +#include + +namespace DispatchEventSupport { + +void dispatchAppServiceEvent(JSContextRef context, const float scale, const std::string bundle); +void dispatchSoftKeyboardChangeEvent(JSContextRef context, const std::string state, const int width, const int height); +void dispatchStorageEvent(JSContextRef context, + const DPL::OptionalStdString& key, + const DPL::OptionalStdString& oldValue, + const DPL::OptionalStdString& newValue, + const std::string& url); +void dispatchHwKeyEvent(Evas_Object* ewkView, const std::string key); +void dispatchAppControlEvent(Evas_Object* ewkView); +} +#endif //_DISPATCH_EVENT_SUPPORT_H_ diff --git a/src_wearable/js-overlay/CMakeLists.txt b/src_wearable/js-overlay/CMakeLists.txt new file mode 100644 index 0000000..f42c3f0 --- /dev/null +++ b/src_wearable/js-overlay/CMakeLists.txt @@ -0,0 +1,67 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 1.0 +# +MACRO(INSTALL_HEADER_FILE HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_JS_OVERLAY}) +ENDMACRO() + +pkg_search_module(webkit2 REQUIRED ewebkit2) +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) + +SET(TARGET_NAME ${TARGET_JS_OVERLAY}) + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/js_function_manager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/js_overlay_functions.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/JSClass + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${webkit2_LIBRARIES} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} + DESTINATION ${DESTINATION_LIB_PREFIX} + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL_HEADER_FILE(js_overlay_types.h) + diff --git a/src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp b/src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp new file mode 100644 index 0000000..dbaff61 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSSoftKeyboardChangeEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + */ + +#include "JSSoftKeyboardChangeEvent.h" +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::SoftKeyboardChangeEvent::Api; + +#define WIDGET_PLUGIN_NAME "SoftKeyboardChangeEvent" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_STATE "state" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_WIDTH "width" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_HEIGHT "height" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace Tizen { +JSClassDefinition JSSoftKeyboardChangeEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSSoftKeyboardChangeEvent::m_property[] = { + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_STATE, + JSSoftKeyboardChangeEvent::getState, + 0, kJSPropertyAttributeReadOnly }, + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_WIDTH, + JSSoftKeyboardChangeEvent::getWidth, + 0, kJSPropertyAttributeReadOnly }, + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_HEIGHT, + JSSoftKeyboardChangeEvent::getHeight, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSSoftKeyboardChangeEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSoftKeyboardChangeEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSSoftKeyboardChangeEvent::m_jsClassRef = JSClassCreate( + JSSoftKeyboardChangeEvent::getClassInfo()); + +void JSSoftKeyboardChangeEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + LogDebug("entered"); + + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + AssertMsg(priv, "Missing private object"); +} + +void JSSoftKeyboardChangeEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + delete priv; + LogDebug("private object is realised"); +} + +JSValueRef JSSoftKeyboardChangeEvent::getState( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered!"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getState()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSSoftKeyboardChangeEvent::getWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered!"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getWidth()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSSoftKeyboardChangeEvent::getHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getHeight()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +ISoftKeyboardChangeEventPtr JSSoftKeyboardChangeEvent::getPrivateObject( + JSObjectRef arg) +{ + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +} +} diff --git a/src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h b/src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h new file mode 100644 index 0000000..49da22f --- /dev/null +++ b/src_wearable/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSSoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H +#define WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H + +#include +#include +#include + +namespace WrtPlugins { +namespace Tizen { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::SoftKeyboardChangeEvent::Api::ISoftKeyboardChangeEventPtr>:: + Type +JSSoftKeyboardChangeEventPrivateObject; + +class JSSoftKeyboardChangeEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getState( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::SoftKeyboardChangeEvent::Api:: + ISoftKeyboardChangeEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // Tizen +} // WrtPlugins + +#endif // WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H diff --git a/src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.cpp b/src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.cpp new file mode 100644 index 0000000..d4ca37f --- /dev/null +++ b/src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSStorageEvent.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + */ + +#include "JSStorageEvent.h" +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::StorageEvent::Api; + +#define WIDGET_PLUGIN_NAME "StorageEvent" + +#define WRT_STORAGE_EVENT_PROPERTY_KEY "key" +#define WRT_STORAGE_EVENT_PROPERTY_OLD_VALUE "oldValue" +#define WRT_STORAGE_EVENT_PROPERTY_NEW_VALUE "newValue" +#define WRT_STORAGE_EVENT_PROPERTY_URL "url" +#define WRT_STORAGE_EVENT_PROPERTY_STORAGE_AREA "storageArea" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + LogError("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace W3C { +JSClassDefinition JSStorageEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSStorageEvent::m_property[] = { + { WRT_STORAGE_EVENT_PROPERTY_KEY, JSStorageEvent::getKey, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_OLD_VALUE, JSStorageEvent::getOldValue, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_NEW_VALUE, JSStorageEvent::getNewValue, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_URL, JSStorageEvent::getUrl, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_STORAGE_AREA, JSStorageEvent::getStorageArea, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSStorageEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSStorageEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSStorageEvent::m_jsClassRef = JSClassCreate( + JSStorageEvent::getClassInfo()); + +void JSStorageEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + LogDebug("entered"); + + JSStorageEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + AssertMsg(priv, "Missing private object"); +} + +void JSStorageEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSStorageEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + delete priv; + LogDebug("private object is realised"); +} + +JSValueRef JSStorageEvent::getKey( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + return converter.toJSValueRef(getPrivateObject(object)->getKey()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getOldValue( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + DPL::OptionalString oldValue = getPrivateObject(object)->getOldValue(); + + if (!oldValue) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(DPL::ToUTF8String(*oldValue)); + } + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getNewValue( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + DPL::OptionalString newValue = getPrivateObject(object)->getNewValue(); + + if (!newValue) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(DPL::ToUTF8String(*newValue)); + } + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getUrl( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + + return converter.toJSValueRef(getPrivateObject(object)->getUrl()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR +} + +JSValueRef JSStorageEvent::getStorageArea( + JSContextRef context, + JSObjectRef /*object*/, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + LogError("Not implemented"); + return JSValueMakeUndefined(context); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +IStorageEventPtr JSStorageEvent::getPrivateObject(JSObjectRef arg) +{ + JSStorageEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +} +} diff --git a/src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.h b/src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.h new file mode 100644 index 0000000..0460f39 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/JSClass/JSStorageEvent.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSStorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_STORAGE_EVENT_H_ +#define _WRT_PLUGIN_JS_STORAGE_EVENT_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::StorageEvent::Api::IStorageEventPtr>::Type +JSStorageEventPrivateObject; + +class JSStorageEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getKey( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getOldValue( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getNewValue( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getUrl( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getStorageArea( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::StorageEvent::Api::IStorageEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // W3C +} // WrtPlugins + +#endif // _WRT_PLUGIN_JS_STORAGE_EVENT_H_ diff --git a/src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp b/src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp new file mode 100644 index 0000000..33fe95b --- /dev/null +++ b/src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSTizenServiceEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + */ + +#include "JSTizenServiceEvent.h" +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::TizenServiceEvent::Api; + +#define WIDGET_PLUGIN_NAME "TizenServiceEvent" + +#define TIZEN_SERVICE_EVENT_PROPERTY_SCALE "scale" +#define TIZEN_SERVICE_EVENT_PROPERTY_BUNDLE "__bundle" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + LogError("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + LogError("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + LogError("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + LogError("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace Tizen { +JSClassDefinition JSTizenServiceEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSTizenServiceEvent::m_property[] = { + { TIZEN_SERVICE_EVENT_PROPERTY_SCALE, JSTizenServiceEvent::getScale, + 0, kJSPropertyAttributeReadOnly }, + { TIZEN_SERVICE_EVENT_PROPERTY_BUNDLE, JSTizenServiceEvent::getBundle, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSTizenServiceEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTizenServiceEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTizenServiceEvent::m_jsClassRef = JSClassCreate( + JSTizenServiceEvent::getClassInfo()); + +void JSTizenServiceEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + LogDebug("entered"); + + JSTizenServiceEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + AssertMsg(priv, "Missing private object"); +} + +void JSTizenServiceEvent::finalize(JSObjectRef object) +{ + LogDebug("entered"); + JSTizenServiceEventPrivateObject* priv = + static_cast(JSObjectGetPrivate( + object)); + + delete priv; + LogDebug("private object is realised"); +} + +JSValueRef JSTizenServiceEvent::getScale( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getScale()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSTizenServiceEvent::getBundle( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getBundle()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +ITizenServiceEventPtr JSTizenServiceEvent::getPrivateObject(JSObjectRef arg) +{ + JSTizenServiceEventPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +} +} diff --git a/src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h b/src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h new file mode 100644 index 0000000..a079dc5 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSTizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ +#define _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace Tizen { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::TizenServiceEvent::Api::ITizenServiceEventPtr>::Type +JSTizenServiceEventPrivateObject; + +class JSTizenServiceEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getScale( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getBundle( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::TizenServiceEvent::Api::ITizenServiceEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // Tizen +} // WrtPlugins + +#endif // _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ diff --git a/src_wearable/js-overlay/deprecated/js_iframe_support.cpp b/src_wearable/js-overlay/deprecated/js_iframe_support.cpp new file mode 100755 index 0000000..904d4e1 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/js_iframe_support.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file IFrameSupport.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +IFrameSupport::IFramesContainer IFrameSupport::m_iframesObject = + IFrameSupport::IFramesContainer(); + +void IFrameSupport::RegisterWidget(java_script_context_t /*global_context*/, + js_object_instance_t iframe, + js_object_instance_t object) +{ + LogDebug("New widget instance registered"); + LogDebug("iframe: " << iframe); + LogDebug("object: " << object); + getIFrameData(static_cast(iframe))->widget = + static_cast(object); +} + +void IFrameSupport::RegisterAddEventListener( + java_script_context_t /*global_context*/, + js_object_instance_t iframe, + js_object_instance_t object) +{ + LogDebug("New addEventListener instance registered"); + LogDebug("iframe: " << iframe); + LogDebug("object: " << object); + getIFrameData(static_cast(iframe))->addEventListener + = static_cast(object); +} + +JSObjectRef IFrameSupport::getIFrameObjectForWidget(JSObjectRef widgetObject) +{ + FOREACH(it, m_iframesObject) + { + if (it->second->widget == widgetObject) { + LogDebug("iframe found"); + return it->first; + } + } + LogDebug("Iframe not found"); + return NULL; +} + +IFrameDataPtr IFrameSupport::getIFrameData(JSObjectRef iframe) +{ + auto it = m_iframesObject.find(iframe); + if (it != m_iframesObject.end()) { + return it->second; + } + + return m_iframesObject[iframe] = IFrameDataPtr(new IFrameData()); +} +} +} diff --git a/src_wearable/js-overlay/deprecated/js_iframe_support.h b/src_wearable/js-overlay/deprecated/js_iframe_support.h new file mode 100755 index 0000000..de07932 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/js_iframe_support.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file IFrameSupport.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_SRC_W3C_WIDGET_IFRAME_SUPPORT_H_ +#define _WRT_PLUGINS_SRC_W3C_WIDGET_IFRAME_SUPPORT_H_ + +#include +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +struct IFrameData +{ + IFrameData() : widget(0), addEventListener(0){} + + JSObjectRef widget; + JSObjectRef addEventListener; +}; +typedef std::shared_ptr IFrameDataPtr; + +class IFrameSupport +{ + public: + static void RegisterWidget(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); + + static void RegisterAddEventListener(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); + + static JSObjectRef getIFrameObjectForWidget(JSObjectRef widgetObject); + + private: + //map iframe:objects + typedef std::map IFramesContainer; + + static IFramesContainer m_iframesObject; + + private: + static IFrameDataPtr getIFrameData(JSObjectRef iframe); +}; +} +} + +#endif diff --git a/src_wearable/js-overlay/deprecated/js_overlay_addEventListener.cpp b/src_wearable/js-overlay/deprecated/js_overlay_addEventListener.cpp new file mode 100755 index 0000000..8cb6801 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/js_overlay_addEventListener.cpp @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file AddEventListenerSupport.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { + +const std::string storageEventName = "storage"; +const std::string appServiceEventName = "appservice"; +const std::string softKeyboardChangeEventName = "softkeyboardchange"; + +AddEventListenerSupport::IFramesListeners +AddEventListenerSupport::m_listeners = + AddEventListenerSupport::IFramesListeners(); + +JSValueRef AddEventListenerSupport::AddEventListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* /*exception*/) +{ + LogDebug("Add event listener invoked"); + LogDebug("This(iframe?):" << thisObject); + LogDebug("object:" << object); + + JSContextRef global_context = JSContextGetGlobalContext(context); + LogDebug("context:" << context << "(global:" << global_context << ")"); + + if (argumentCount < 2 || !JSValueIsString(context, arguments[0])) { + LogError("Wrong arguments"); + return JSValueMakeUndefined(context); + } + + std::string eventName = WrtDeviceApis::CommonsJavaScript:: + Converter(context).toString(arguments[0]); + LogDebug("Event name: " << eventName); + + if (eventName != storageEventName && + eventName != appServiceEventName && + eventName != softKeyboardChangeEventName) + { + LogDebug("Event type not supported"); + return JSValueMakeUndefined(context); + } + + JSObjectRef objectCb = JSValueToObject(context, arguments[1], NULL); + if (!JSObjectIsFunction(context, objectCb)) { + LogError("JS object is not a function"); + return JSValueMakeUndefined(context); + } + JSValueProtect(global_context, arguments[1]); + //add object to Listeners + //set event information according to each event type + CallbackData data; + data.object = objectCb; + data.thisObject = thisObject; + data.context = global_context; + + if (eventName == storageEventName) { + data.eventType = StorageCustomEvent; + } else if (eventName == appServiceEventName) { + data.eventType = ServiceCustomEvent; + } else if (eventName == softKeyboardChangeEventName) { + data.eventType = SoftKeyboardChangeCustomEvent; + } + + getIFrameListeners(thisObject)->push_back(data); + + return JSValueMakeUndefined(context); +} + +void AddEventListenerSupport::RemoveIFrame(JSObjectPtr iframe) +{ + auto it = m_listeners.find(iframe->getObject()); + if (it == m_listeners.end()) { + LogWarning("Iframe not registered"); + return; + } + + FOREACH(listener, *it->second) + { + JSValueUnprotect(listener->context, listener->object); + } + m_listeners.erase(it); + LogDebug("Iframe removed from add event listener object"); +} + +void AddEventListenerSupport::CallStorageListenersFromDifferentIFrames( + JSObjectRef iframe, + const WrtDeviceApis::StorageEvent::Api::IStorageEventPtr& event) +{ + LogDebug("Invoked callbacks"); + + FOREACH(it, m_listeners) + { + if (it->first == iframe) { + continue; + } + + FOREACH(listener, *it->second) + { + LogDebug("Call"); + + auto eventPriv = + new JSStorageEventPrivateObject(listener->context, event); + + JSObjectRef eventObject = + JSObjectMake(listener->context, JSStorageEvent::getClassRef(), eventPriv); + const size_t argc = 1; + JSValueRef argv[argc] = { eventObject }; + + JSValueProtect(listener->context, eventObject); + + if (listener->eventType == StorageCustomEvent) + { + JSObjectCallAsFunction( + listener->context, + listener->object, + NULL, + argc, + argv, + NULL); + } + + JSValueUnprotect(listener->context, eventObject); + } + } + + LogDebug("Done"); +} + +void AddEventListenerSupport::CallCustomEventListenersFromIFrame( + JSObjectRef iframe, + CustomEventType eventType, + JSObjectRef eventObject) +{ + LogDebug("Invoked callbacks"); + + IFramesListeners::iterator it = m_listeners.find(iframe); + if (it == m_listeners.end()) { + LogDebug("This frame object not existed"); + return; + } + + const size_t argc = 1; + JSValueRef argv[argc] = { eventObject }; + + FOREACH(listener, *it->second) + { + if (listener->eventType == eventType) { + LogDebug("Call"); + JSObjectCallAsFunction( + listener->context, + listener->object, + iframe, + argc, + argv, + NULL); + } + } + LogDebug("Done"); +} + +AddEventListenerSupport::ListenersPtr +AddEventListenerSupport::getIFrameListeners(JSObjectRef iframe) +{ + auto it = m_listeners.find(iframe); + if (it != m_listeners.end()) { + return it->second; + } + + return m_listeners[iframe] = ListenersPtr(new Listeners()); +} +} +} diff --git a/src_wearable/js-overlay/deprecated/js_overlay_addEventListener.h b/src_wearable/js-overlay/deprecated/js_overlay_addEventListener.h new file mode 100755 index 0000000..0a9717e --- /dev/null +++ b/src_wearable/js-overlay/deprecated/js_overlay_addEventListener.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file js_overlay_addEventListener.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_SRC_W3C_WIDGET_ADDEVENTLISTENERSUPPORT_H_ +#define _WRT_PLUGINS_SRC_W3C_WIDGET_ADDEVENTLISTENERSUPPORT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// import temporarily from JSContextRefPrivate.h +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +namespace WrtPlugins { +namespace W3C { +class AddEventListenerSupport +{ + public: + static JSValueRef AddEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static void RemoveIFrame(JSObjectPtr iframe); + + static void CallStorageListenersFromDifferentIFrames( + JSObjectRef iframe, + const WrtDeviceApis::StorageEvent::Api::IStorageEventPtr& event); + + static void CallCustomEventListenersFromIFrame( + JSObjectRef iframe, + CustomEventType eventType, + JSObjectRef eventObject); + + private: + + struct CallbackData { + CustomEventType eventType; + JSObjectRef object; + JSObjectRef thisObject; + JSContextRef context; + }; + + typedef std::list Listeners; + typedef std::shared_ptr ListenersPtr; + + //first-iframe, 2nd - listeners list + typedef std::map IFramesListeners; + + static IFramesListeners m_listeners; + + private: + static ListenersPtr getIFrameListeners(JSObjectRef iframe); +}; +} +} + +#endif diff --git a/src_wearable/js-overlay/deprecated/js_overlay_support.cpp b/src_wearable/js-overlay/deprecated/js_overlay_support.cpp new file mode 100644 index 0000000..cad75a5 --- /dev/null +++ b/src_wearable/js-overlay/deprecated/js_overlay_support.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_overlay_support.cpp + * @author + * @version 1.0 + * @brief + */ +#include +#include +#include +#include + +#include + +namespace JSOverlaySupport { +class JSFunctionDispatcher +{ + public: + struct PrivateData + { + //required to unprotect object in destructor; + JSContextRef context; + JSObjectPtr originalFunction; + JSObjectPtr overlayFunction; + }; + + static JSClassRef getClassRef(); + + private: + static JSClassDefinition m_classInfo; + + private: + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef callAsFunction(JSContextRef ctx, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +JSObjectPtr createWrappedFunction( + JSGlobalContextRef ctx, + const JSObjectPtr& originalFunction, + const JSObjectPtr& overlayFunction, + const std::string& name) +{ + LogDebug("Creation overlay for function: " << name); + JSStringRef name_js = JSStringCreateWithUTF8CString(name.c_str()); + + JSFunctionDispatcher::PrivateData* priv = + new JSFunctionDispatcher::PrivateData; + priv->context = ctx; + priv->overlayFunction = overlayFunction; + priv->originalFunction = originalFunction; + + auto fun = JSObjectMake(ctx, JSFunctionDispatcher::getClassRef(), priv); + + JSStringRelease(name_js); + + LogDebug("JSValueProtect invoked for: " + << overlayFunction->getObject() << " " + << originalFunction->getObject() << " Wrapper:" + << fun); + + //the value is unprotected in finalize of the JSFunctionDispatcher object + JSValueProtect(ctx, + static_cast( + overlayFunction->getObject())); + + return JSObjectPtr(new JSObject(fun)); +} + +JSClassDefinition JSFunctionDispatcher::m_classInfo = { + 0, + kJSClassAttributeNone, + "IGNORED", + 0, + 0, + 0, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + callAsFunction, + NULL, + NULL, + NULL +}; + +JSClassRef JSFunctionDispatcher::getClassRef() +{ + static auto classRef = JSClassCreate(&m_classInfo); + return classRef; +} + +void JSFunctionDispatcher::initialize(JSContextRef /*context*/, + JSObjectRef /*object*/) +{ + LogDebug("Initialize"); +} + +void JSFunctionDispatcher::finalize(JSObjectRef object) +{ + LogDebug("finalize"); + + PrivateData* priv = static_cast(JSObjectGetPrivate(object)); + if (priv) { + JSValueUnprotect(priv->context, + static_cast( + priv->overlayFunction->getObject())); + delete priv; + } +} + +JSValueRef JSFunctionDispatcher::callAsFunction( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LogDebug("Dispatcher invoked"); + + JSValueRef result = JSValueMakeUndefined(context); + + JSFunctionDispatcher::PrivateData* priv = + static_cast + (JSObjectGetPrivate(object)); + + if (!priv) { + LogError("Private object is NULL"); + return result; + } + + //call overlayed function + if (priv->overlayFunction->getObject()) { + LogDebug("Overlayed function will be invoked..."); + result = JSObjectCallAsFunction( + priv->context, + static_cast( + priv->overlayFunction->getObject()), + thisObject, + argumentCount, + arguments, + exception); + } + + //call original function + if (priv->originalFunction->getObject()) { + LogDebug("Original function will be invoked.."); + result = JSObjectCallAsFunction( + context, + static_cast( + priv->originalFunction->getObject()), + thisObject, + argumentCount, + arguments, + exception); + } + + LogDebug("Done"); + return result; +} +} diff --git a/src_wearable/js-overlay/deprecated/js_overlay_support.h b/src_wearable/js-overlay/deprecated/js_overlay_support.h new file mode 100644 index 0000000..0cfb19b --- /dev/null +++ b/src_wearable/js-overlay/deprecated/js_overlay_support.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_function_wrapper.h + * @author + * @version 1.0 + * @brief + */ + +#ifndef _JAVASCRIPT_OVERLAY_SUPPORT_H +#define _JAVASCRIPT_OVERLAY_SUPPORT_H + +#include +#include +#include +#include +#include + +namespace JSOverlaySupport { +JSObjectPtr createWrappedFunction( + JSGlobalContextRef ctx, + const JSObjectPtr& originalFunction, + const JSObjectPtr& overlayFunction, + const std::string& name); +} + +#endif diff --git a/src_wearable/js-overlay/js_function_manager.cpp b/src_wearable/js-overlay/js_function_manager.cpp new file mode 100644 index 0000000..dab34b9 --- /dev/null +++ b/src_wearable/js-overlay/js_function_manager.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_function_manager.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @author Yunchan Cho (yunchan.cho@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include +#include +#include + +IMPLEMENT_SAFE_SINGLETON(JsFunctionManager) + +namespace { +const char* JSPRINT_NAME = "jsPrint"; +const char* JSGLOBAL_OBJECT = "GLOBAL_OBJECT"; +const char* JSHOOK_NAME = "jsHook"; +} + +namespace JavaScriptFunctions { +//options +class_definition_options_t jsHookfunctionsOptions = { + JS_FUNCTION, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + reinterpret_cast(JSCFunctions::JavaScriptHookProc) +}; + +class_definition_options_t jsPrintfunctionsOptions = { + JS_FUNCTION, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + reinterpret_cast(JSCFunctions::JavaScriptPrintProc) +}; + +js_entity_definition_t jsPrint = { + JSGLOBAL_OBJECT, + JSPRINT_NAME, + "", + NULL, + NULL, + &jsPrintfunctionsOptions +}; + +js_entity_definition_t jsHook = { + JSGLOBAL_OBJECT, + JSHOOK_NAME, + "", + NULL, + NULL, + &jsHookfunctionsOptions +}; + +const js_entity_definition_ptr_t jsPrintPtr = &jsPrint; +const js_entity_definition_ptr_t jsHookPtr = &jsHook; +} + +bool JsFunctionManager::initialize() +{ + _D("JSObjectDeclaration for js functions are intialized"); + JSObjectDeclarationPtr jsPrintObj( + new JSObjectDeclaration(JavaScriptFunctions::jsPrintPtr)); + + JSObjectDeclarationPtr jsHookObj( + new JSObjectDeclaration(JavaScriptFunctions::jsHookPtr)); + + m_functions.push_back(jsPrintObj); + m_functions.push_back(jsHookObj); + + return true; +} + +JsFunctionManager::Functions JsFunctionManager::getFunctions() +{ + _D("get standard js fucntions"); + static bool initialized = initialize(); + (void) initialized; + return m_functions; +} diff --git a/src_wearable/js-overlay/js_function_manager.h b/src_wearable/js-overlay/js_function_manager.h new file mode 100644 index 0000000..d6bd80e --- /dev/null +++ b/src_wearable/js-overlay/js_function_manager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_function_manager.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_FUNCTION_MANGER_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_FUNCTION_MANGER_H_ + +#include +#include +#include + +#include + +class JsFunctionManager : private DPL::Noncopyable +{ + public: + typedef std::list Functions; + + public: + Functions getFunctions(); + + private: + JsFunctionManager() + {} + + bool initialize(); + + private: + Functions m_functions; + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton JsFunctionManagerSingleton; + +#endif + diff --git a/src_wearable/js-overlay/js_overlay_functions.cpp b/src_wearable/js-overlay/js_overlay_functions.cpp new file mode 100644 index 0000000..8097d20 --- /dev/null +++ b/src_wearable/js-overlay/js_overlay_functions.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file javascript_functions.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include + +namespace JSCFunctions { +std::string ConvertJSStringToStdString(JSStringRef value) +{ + int nSize = JSStringGetLength(value) + 1; + DPL::ScopedArray textStr(new char[nSize]); + JSStringGetUTF8CString(value, textStr.Get(), nSize); + std::string ret = textStr.Get(); + return ret; +} + +JSValueRef JavaScriptPrintProc(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + if (argumentCount == 0 || !JSValueIsString(context, arguments[0])) { + LogError("Argument is not string"); + return JSValueMakeUndefined(context); + } + + JSStringRef textRef = JSValueToStringCopy(context, arguments[0], exception); + int nSize = JSStringGetLength(textRef) + 1; + + DPL::ScopedArray textStr(new char[nSize]); + + JSStringGetUTF8CString(textRef, textStr.Get(), nSize); + LogDebug("\033[00;35m[jsPrint] " << textStr.Get()); + + JSStringRelease(textRef); + return JSValueMakeBoolean(context, true); +} + +JSValueRef JavaScriptHookProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + bool inError = false; + if (argumentCount < 2 || + argumentCount > 3 || + !JSValueIsString(context, arguments[0]) || + !JSValueIsString(context, arguments[1])) + { + inError = true; + } + + if (inError) { + LogError("*********************************************"); + LogError("*********************************************"); + LogError("Cannot print test Result"); + LogError("*********************************************"); + LogError("*********************************************"); + return JSValueMakeUndefined(context); + } + + std::string id, result, message; + JSStringRef idRef = JSValueToStringCopy(context, arguments[0], exception); + id = ConvertJSStringToStdString(idRef); + JSStringRelease(idRef); + JSStringRef idResult = JSValueToStringCopy(context, + arguments[1], + exception); + result = ConvertJSStringToStdString(idResult); + JSStringRelease(idResult); + + if (argumentCount == 3 && !JSValueIsString(context, arguments[2])) { + JSStringRef idMessage = JSValueToStringCopy(context, + arguments[0], + exception); + message = ConvertJSStringToStdString(idMessage); + JSStringRelease(idMessage); + } + + LogDebug("\033[00;35m***********************************************"); + LogDebug("\033[00;35m***********************************************"); + LogDebug("\033[00;35m TEST ID: " << id); + LogDebug("\033[00;35m RESULT: " << result); + LogDebug("\033[00;35m MESSAGE: " << message); + LogDebug("\033[00;35m***********************************************"); + LogDebug("\033[00;35m***********************************************"); + + return JSValueMakeBoolean(context, true); +} +} diff --git a/src_wearable/js-overlay/js_overlay_functions.h b/src_wearable/js-overlay/js_overlay_functions.h new file mode 100644 index 0000000..3c7f86a --- /dev/null +++ b/src_wearable/js-overlay/js_overlay_functions.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file javascript_functions.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_EFL_JAVASCRIPT_FUNCTIONS_H_ +#define WRT_SRC_PLUGIN_SERVICE_EFL_JAVASCRIPT_FUNCTIONS_H_ + +#include + +namespace JSCFunctions { +JSValueRef JavaScriptPrintProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); +JSValueRef JavaScriptHookProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); +} + +#endif + diff --git a/src_wearable/js-overlay/js_overlay_types.h b/src_wearable/js-overlay/js_overlay_types.h new file mode 100644 index 0000000..e47634f --- /dev/null +++ b/src_wearable/js-overlay/js_overlay_types.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file js_overlay_types.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ +#define _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ + +#include + +namespace WrtPlugins { +namespace W3C { +// If needed, enum for new custom event should be defined here +enum CustomEventType { + StorageCustomEvent, + ServiceCustomEvent, + SoftKeyboardChangeCustomEvent, +}; + +// Argument structure of SoftKeyboardChangeCustomEvent +typedef struct SoftKeyboardChangeArgs { + std::string state; // value is 'on' or 'off' + int width; + int height; + SoftKeyboardChangeArgs() : + width(0), + height(0) + {} +} SoftKeyboardChangeArgs; + +// If needed, argument structure of other custom events should be defined here +} // W3C +} // WrtPlugins +#endif // _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ diff --git a/src_wearable/modules/API/CMakeLists.txt b/src_wearable/modules/API/CMakeLists.txt new file mode 100644 index 0000000..1a64e70 --- /dev/null +++ b/src_wearable/modules/API/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include_config_file(Filesystem) +include_config_file(Widget) +include_config_file(LocalStorage) +include_config_file(WidgetDB) +include_config_file(PluginManager) +include_config_file(StorageEvent) +include_config_file(TizenServiceEvent) +include_config_file(SoftKeyboardChangeEvent) diff --git a/src_wearable/modules/API/DESCRIPTION b/src_wearable/modules/API/DESCRIPTION new file mode 100644 index 0000000..76eb35c --- /dev/null +++ b/src_wearable/modules/API/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Platform independent platform API diff --git a/src_wearable/modules/API/Filesystem/Enums.h b/src_wearable/modules/API/Filesystem/Enums.h new file mode 100644 index 0000000..81e7d0d --- /dev/null +++ b/src_wearable/modules/API/Filesystem/Enums.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_ENUMS_H_ +#define WRTDEVICEAPIS_FILESYSTEM_ENUMS_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +enum LocationType +{ + LT_APPS, + LT_DOCUMENTS, + LT_DOWNLOADS, + LT_GAMES, + LT_IMAGES, + LT_OTHERS, + LT_ROOT, + LT_SDCARD, + LT_SOUNDS, + LT_TEMP, + LT_VIDEOS +}; + +enum NodeType +{ + NT_DIRECTORY, + NT_FILE +}; + +enum AccessMode +{ + AM_READ = 0x0001, + AM_WRITE = 0x0002, + AM_APPEND = 0x0004 +}; + +/** + * Used in @see IManager::access(). + */ +enum AccessType +{ + 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 + AT_EXISTS = 0x0008 //!< AT_EXISTS - checks for existence +}; + +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 FiltersMap; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_ENUMS_H_ */ diff --git a/src_wearable/modules/API/Filesystem/EventCopy.cpp b/src_wearable/modules/API/Filesystem/EventCopy.cpp new file mode 100644 index 0000000..f6b6e56 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventCopy.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventCopy.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventCopy::EventCopy(const IPathPtr& src, + const IPathPtr& dest) : + m_src(src), + m_dest(dest), + m_options(OPT_NONE) +{ + AssertMsg(src, "Source path not set."); + AssertMsg(dest, "Destination path not set."); +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventCopy.h b/src_wearable/modules/API/Filesystem/EventCopy.h new file mode 100644 index 0000000..62bef44 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventCopy.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTCOPY_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTCOPY_H_ + +#include +#include +#include "IPath.h" +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventCopy : public Commons::IEvent +{ + 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 + // WrtDeviceApis::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr EventCopyPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTCOPY_H_ diff --git a/src_wearable/modules/API/Filesystem/EventFind.cpp b/src_wearable/modules/API/Filesystem/EventFind.cpp new file mode 100644 index 0000000..c8c01a9 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventFind.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventFind.h" + +#include +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +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(name, value)); +} + +FiltersMap EventFind::getFilters() const +{ + return m_filters; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventFind.h b/src_wearable/modules/API/Filesystem/EventFind.h new file mode 100644 index 0000000..47d6e50 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventFind.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_IEVENTFILESYSTEMFIND_H_ +#define WRTDEVICEAPIS_IEVENTFILESYSTEMFIND_H_ + +#include +#include +#include +#include "IPath.h" +#include "INodeTypes.h" +#include "Enums.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventFind : public Commons::IEvent +{ + 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 EventFindPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_IEVENTFILESYSTEMFIND_H_ diff --git a/src_wearable/modules/API/Filesystem/EventListNodes.cpp b/src_wearable/modules/API/Filesystem/EventListNodes.cpp new file mode 100644 index 0000000..80c2dd2 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventListNodes.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventListNodes.h" +#include +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventListNodes::EventListNodes(const INodePtr& node) : m_node(node) +{ + AssertMsg(m_node, "Node can't be NULL."); +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventListNodes.h b/src_wearable/modules/API/Filesystem/EventListNodes.h new file mode 100644 index 0000000..a856546 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventListNodes.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTLISTNODES_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTLISTNODES_H_ + +#include +#include +#include "INodeTypes.h" +#include "NodeFilter.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventListNodes : public Commons::IEvent +{ + 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 EventListNodesPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTLISTNODES_H_ diff --git a/src_wearable/modules/API/Filesystem/EventMove.cpp b/src_wearable/modules/API/Filesystem/EventMove.cpp new file mode 100644 index 0000000..481dac7 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventMove.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventMove.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventMove::EventMove(const IPathPtr& src, + const IPathPtr& dest) : + m_src(src), + m_dest(dest), + m_options(OPT_NONE) +{ + AssertMsg(src, "Source path not set."); + AssertMsg(dest, "Destination path not set."); +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventMove.h b/src_wearable/modules/API/Filesystem/EventMove.h new file mode 100644 index 0000000..d9716f0 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventMove.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTMOVE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTMOVE_H_ + +#include +#include +#include "IPath.h" +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventMove : public Commons::IEvent +{ + 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 + // WrtDeviceApis::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr EventMovePtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTMOVE_H_ diff --git a/src_wearable/modules/API/Filesystem/EventOpen.cpp b/src_wearable/modules/API/Filesystem/EventOpen.cpp new file mode 100644 index 0000000..274e963 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventOpen.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventOpen.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventOpen.h b/src_wearable/modules/API/Filesystem/EventOpen.h new file mode 100644 index 0000000..5ab5662 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventOpen.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTOPEN_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTOPEN_H_ + +#include +#include +#include "IStream.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventOpen : public Commons::IEvent +{ + 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); + + private: + int m_mode; ///< Mode. + IStreamPtr m_stream; ///< Opened stream. +}; + +typedef DPL::SharedPtr EventOpenPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTOPEN_H_ diff --git a/src_wearable/modules/API/Filesystem/EventReadText.cpp b/src_wearable/modules/API/Filesystem/EventReadText.cpp new file mode 100644 index 0000000..560687e --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventReadText.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventReadText.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +std::string EventReadText::getResult() const +{ + return m_result; +} + +void EventReadText::setResult(const std::string& result) +{ + m_result = result; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventReadText.h b/src_wearable/modules/API/Filesystem/EventReadText.h new file mode 100644 index 0000000..986b565 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventReadText.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTREADTEXT_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTREADTEXT_H_ + +#include +#include +#include +#include "IPath.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventReadText : public Commons::IEvent +{ + public: + /** + * Gets read text. + * @return Text. + */ + std::string getResult() const; + + /** + * Sets read text. + * @param result Text. + */ + void setResult(const std::string& result); + + private: + std::string m_result; ///< Read text. +}; + +typedef DPL::SharedPtr EventReadTextPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTREADTEXT_H_ diff --git a/src_wearable/modules/API/Filesystem/EventRemove.cpp b/src_wearable/modules/API/Filesystem/EventRemove.cpp new file mode 100644 index 0000000..308a66b --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventRemove.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventRemove.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventRemove::EventRemove(const IPathPtr& path) : + m_path(path), + m_options(OPT_NONE) +{ + AssertMsg(m_path, "Path is not set."); +} + +IPathPtr EventRemove::getPath() const +{ + return m_path; +} + +int EventRemove::getOptions() const +{ + return m_options; +} + +void EventRemove::setOptions(int options) +{ + m_options = options; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventRemove.h b/src_wearable/modules/API/Filesystem/EventRemove.h new file mode 100644 index 0000000..be3aecd --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventRemove.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTREMOVE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTREMOVE_H_ + +#include +#include +#include "INode.h" +#include "Enums.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventRemove : public Commons::IEvent +{ + 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 + // WrtDeviceApis::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr EventRemovePtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTREMOVE_H_ diff --git a/src_wearable/modules/API/Filesystem/EventResolve.cpp b/src_wearable/modules/API/Filesystem/EventResolve.cpp new file mode 100644 index 0000000..2473795 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventResolve.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "EventResolve.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +EventResolve::EventResolve(const IPathPtr& path) : m_path(path) +{} + +IPathPtr EventResolve::getPath() const +{ + return m_path; +} + +INodePtr EventResolve::getResult() const +{ + return m_node; +} + +void EventResolve::setResult(const INodePtr& node) +{ + m_node = node; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/EventResolve.h b/src_wearable/modules/API/Filesystem/EventResolve.h new file mode 100644 index 0000000..1d50258 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/EventResolve.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_EVENTRESOLVE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_EVENTRESOLVE_H_ + +#include +#include +#include "IPath.h" +#include "INode.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class EventResolve : public Commons::IEvent +{ + 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); + + private: + IPathPtr m_path; ///< Path to the requested node. + INodePtr m_node; ///< Resolved node. +}; + +typedef DPL::SharedPtr EventResolvePtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_EVENTRESOLVE_H_ diff --git a/src_wearable/modules/API/Filesystem/IManager.cpp b/src_wearable/modules/API/Filesystem/IManager.cpp new file mode 100644 index 0000000..92219f5 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/IManager.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include "IManager.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +IManager& IManager::getInstance() +{ + static Manager instance; + return instance; +} + +bool IManager::fileExists(const std::string &file) +{ + return WrtDeviceApis::Filesystem::Manager::fileExists(file); +} + +IManager::IManager() : + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD) +{} + +IManager::~IManager() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/IManager.h b/src_wearable/modules/API/Filesystem/IManager.h new file mode 100644 index 0000000..bc3cf0d --- /dev/null +++ b/src_wearable/modules/API/Filesystem/IManager.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_IMANAGER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_IMANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +typedef std::vector LocationPaths; +typedef std::vector LocationTypes; + +class IManager : + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver +{ + public: + static IManager& getInstance(); + static bool fileExists(const std::string &file); + + virtual ~IManager() = 0; + + /** + * Gets base path. + * @return Valid path or empty shared pointer. + */ + virtual IPathPtr getBasePath() const = 0; + + /** + * Gets path for specified location type. + * @param type Location type @see + * WrtDeviceApis::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; + + /** + * 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; + + protected: + IManager(); + + virtual void OnRequestReceived(const EventResolvePtr& event) = 0; + virtual void OnRequestReceived(const EventCopyPtr& event) = 0; + virtual void OnRequestReceived(const EventMovePtr& event) = 0; + virtual void OnRequestReceived(const EventRemovePtr& event) = 0; + virtual void OnRequestReceived(const EventFindPtr& event) = 0; +}; // IManager +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_IMANAGER_H_ diff --git a/src_wearable/modules/API/Filesystem/INode.cpp b/src_wearable/modules/API/Filesystem/INode.cpp new file mode 100644 index 0000000..cd30a04 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/INode.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "INode.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +INode::INode() : + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD), + Commons::EventRequestReceiver( + Commons::ThreadEnum::FILESYSTEM_THREAD) +{} + +INode::~INode() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/INode.h b/src_wearable/modules/API/Filesystem/INode.h new file mode 100644 index 0000000..c227aa9 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/INode.h @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_INODE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_INODE_H_ + +#include +#include +#include +#include +#include +#include +#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 WrtDeviceApis { +namespace Filesystem { +namespace Api { +class INode : + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver, + public Commons::EventRequestReceiver +{ + public: + typedef std::vector 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 /*DEPREC*/ = 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 std::size_t 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; + + protected: + INode(); +}; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_INODE_H_ */ diff --git a/src_wearable/modules/API/Filesystem/INodeTypes.h b/src_wearable/modules/API/Filesystem/INodeTypes.h new file mode 100644 index 0000000..c1c49f7 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/INodeTypes.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_INODETYPES_H_ +#define WRTDEVICEAPIS_FILESYSTEM_INODETYPES_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class INode; + +typedef DPL::SharedPtr INodePtr; + +typedef std::vector NodeList; +typedef NodeList::iterator NodeListIterator; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_INODETYPES_H_ diff --git a/src_wearable/modules/API/Filesystem/IPath.cpp b/src_wearable/modules/API/Filesystem/IPath.cpp new file mode 100644 index 0000000..de9b32d --- /dev/null +++ b/src_wearable/modules/API/Filesystem/IPath.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "IPath.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +IPathPtr IPath::create(const std::string& str) +{ + return Path::create(str); +} + +IPath::SeparatorType IPath::getSeparator() +{ + return Path::getSeparator(); +} + +IPath::~IPath() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/IPath.h b/src_wearable/modules/API/Filesystem/IPath.h new file mode 100644 index 0000000..3c32abd --- /dev/null +++ b/src_wearable/modules/API/Filesystem/IPath.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_IPATH_H_ +#define WRTDEVICEAPIS_FILESYSTEM_IPATH_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class IPath; +typedef DPL::SharedPtr 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 bool operator==(const IPath& lhs, const IPath& rhs) +{ + return (lhs.getFullPath() == rhs.getFullPath()); +} + +inline bool operator==(const IPath& lhs, const std::string& rhs) +{ + return (lhs.getFullPath() == rhs); +} + +inline bool operator==(const std::string& lhs, const IPath& rhs) +{ + return (lhs == rhs.getFullPath()); +} + +inline bool operator!=(const IPath& lhs, const IPath& rhs) +{ + return (lhs.getFullPath() != rhs.getFullPath()); +} + +inline bool operator!=(const IPath& lhs, const std::string& rhs) +{ + return (lhs.getFullPath() != rhs); +} + +inline bool operator!=(const std::string& lhs, const IPath& rhs) +{ + return (lhs != rhs.getFullPath()); +} +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_IPATH_H_ diff --git a/src_wearable/modules/API/Filesystem/IStream.cpp b/src_wearable/modules/API/Filesystem/IStream.cpp new file mode 100644 index 0000000..b18f188 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/IStream.cpp @@ -0,0 +1,25 @@ +/* + * 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 "IStream.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +IStream::~IStream() +{} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/IStream.h b/src_wearable/modules/API/Filesystem/IStream.h new file mode 100644 index 0000000..d39ddb0 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/IStream.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_ISTREAM_H_ +#define WRTDEVICEAPIS_FILESYSTEM_ISTREAM_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +class IStream; +typedef DPL::SharedPtr 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 long getSize() const = 0; +}; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_ISTREAM_H_ */ diff --git a/src_wearable/modules/API/Filesystem/NodeFilter.cpp b/src_wearable/modules/API/Filesystem/NodeFilter.cpp new file mode 100644 index 0000000..b26e275 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/NodeFilter.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "NodeFilter.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +OptionalString NodeFilter::getName() const +{ + return m_name; +} + +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; +} +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/NodeFilter.h b/src_wearable/modules/API/Filesystem/NodeFilter.h new file mode 100644 index 0000000..3b77ff3 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/NodeFilter.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_NODEFILTER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_NODEFILTER_H_ + +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +typedef boost::optional OptionalString; +typedef boost::optional OptionalDate; +typedef boost::optional OptionalSize; + +class NodeFilter +{ + public: + 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); + + private: + OptionalString m_name; + Commons::Range m_created; + Commons::Range m_modified; + Commons::Range m_size; +}; + +typedef DPL::SharedPtr NodeFilterPtr; +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_NODEFILTER_H_ diff --git a/src_wearable/modules/API/Filesystem/PathUtils.cpp b/src_wearable/modules/API/Filesystem/PathUtils.cpp new file mode 100644 index 0000000..e2ac7de --- /dev/null +++ b/src_wearable/modules/API/Filesystem/PathUtils.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "PathUtils.h" +#include + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +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) { + result.push_back(IPath::create(fullPath.substr(0, pos))); + } + return result; +} +} // PathUtils +} // API +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/API/Filesystem/PathUtils.h b/src_wearable/modules/API/Filesystem/PathUtils.h new file mode 100644 index 0000000..40642f3 --- /dev/null +++ b/src_wearable/modules/API/Filesystem/PathUtils.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_PATHUTILS_H_ +#define WRTDEVICEAPIS_FILESYSTEM_PATHUTILS_H_ + +#include +#include "IPath.h" + +namespace WrtDeviceApis { +namespace Filesystem { +namespace Api { +namespace PathUtils { +typedef std::vector 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 +} // API +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_PATHUTILS_H_ diff --git a/src_wearable/modules/API/Filesystem/config.cmake b/src_wearable/modules/API/Filesystem/config.cmake new file mode 100644 index 0000000..a9a514b --- /dev/null +++ b/src_wearable/modules/API/Filesystem/config.cmake @@ -0,0 +1,25 @@ +get_current_path() + +set(API_FILESYSTEM_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_FILESYSTEM + ${CURRENT_PATH}/IManager.cpp + ${CURRENT_PATH}/IPath.cpp + ${CURRENT_PATH}/IStream.cpp + ${CURRENT_PATH}/EventResolve.cpp + ${CURRENT_PATH}/EventCopy.cpp + ${CURRENT_PATH}/EventMove.cpp + ${CURRENT_PATH}/EventRemove.cpp + ${CURRENT_PATH}/EventFind.cpp + ${CURRENT_PATH}/EventListNodes.cpp + ${CURRENT_PATH}/EventOpen.cpp + ${CURRENT_PATH}/EventReadText.cpp + ${CURRENT_PATH}/INode.cpp + ${CURRENT_PATH}/NodeFilter.cpp + ${CURRENT_PATH}/PathUtils.cpp + PARENT_SCOPE +) + diff --git a/src_wearable/modules/API/LocalStorage/ILocalStorage.h b/src_wearable/modules/API/LocalStorage/ILocalStorage.h new file mode 100644 index 0000000..9532984 --- /dev/null +++ b/src_wearable/modules/API/LocalStorage/ILocalStorage.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Local storage interface file + */ + +#ifndef WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_INTERFACE_H_ +#define WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_INTERFACE_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +class ILocalStorage +{ + public: + + /** + * Save pair key/value in local storage + * @param key + * @param value + * @param readOnly - if true, the value will be read only + * otherwise the value will be modificable + */ + virtual void setItem(const std::string& key, + const std::string& value, + bool readOnly) = 0; + + /** + * Remove pair key/value from local storage + */ + virtual void removeItem(const std::string& key) = 0; + + /** + * Get value for key + * + */ + virtual DPL::OptionalStdString getValue( + const std::string& key) const = 0; + + /** + * Clears the local storage + * @param removeReadOnly - true -remove all elements + * false - ommit items which have read only flag + * set + */ + virtual void clear(bool removeReadOnly) = 0; + + /** + * Get number of elements in local storage + * @param removeReadOnly - true -remove all elements + * false - ommit items which have read only flag + * set + */ + virtual size_t getStorageSize() const = 0; + + /** + * Get key name for index + */ + virtual std::string getKeyByIndex(size_t index) const = 0; + + /** + * virtual destructor + */ + virtual ~ILocalStorage() + {} +}; + +typedef DPL::SharedPtr ILocalStoragePtr; +} // Api +} // LocalStorage +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_LOCALSTORAGE_LOACA_STORAGE_INTERFACE_H_ diff --git a/src_wearable/modules/API/LocalStorage/LocalStorageMgr.cpp b/src_wearable/modules/API/LocalStorage/LocalStorageMgr.cpp new file mode 100644 index 0000000..04e9cc8 --- /dev/null +++ b/src_wearable/modules/API/LocalStorage/LocalStorageMgr.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file LocalStorageMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ +#include "LocalStorageMgr.h" +#include + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +ILocalStoragePtr getLocalStorage(int widgetId) +{ + return ILocalStoragePtr(new WrtDeviceApis::WidgetInterfaceObject(widgetId)); +} +} // Api +} // LocalStorage +} // WrtDeviceApis diff --git a/src_wearable/modules/API/LocalStorage/LocalStorageMgr.h b/src_wearable/modules/API/LocalStorage/LocalStorageMgr.h new file mode 100644 index 0000000..c892376 --- /dev/null +++ b/src_wearable/modules/API/LocalStorage/LocalStorageMgr.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file LocalStorageMgr.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H +#define WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H + +#include + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +ILocalStoragePtr getLocalStorage(int widgetId); +} // Api +} // LocalStorage +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H + diff --git a/src_wearable/modules/API/LocalStorage/config.cmake b/src_wearable/modules/API/LocalStorage/config.cmake new file mode 100644 index 0000000..f421686 --- /dev/null +++ b/src_wearable/modules/API/LocalStorage/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_LOCALSTORAGE_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_LOCALSTORAGE + ${CURRENT_PATH}/LocalStorageMgr.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/API/PluginManager/IPluginManager.h b/src_wearable/modules/API/PluginManager/IPluginManager.h new file mode 100644 index 0000000..d96652c --- /dev/null +++ b/src_wearable/modules/API/PluginManager/IPluginManager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IPluginManager.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ +#define WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +class IPluginManager +{ + public: + typedef std::vector PropertyList; + + virtual ~IPluginManager() {} + virtual bool hasChild(const std::string &name) const = 0; + virtual bool loadChild(const std::string &name) const = 0; + + virtual JSValueRef getProperty(const std::string &name) const = 0; + virtual bool setProperty(const std::string &name, + JSValueRef value) = 0; + virtual bool deleteProperty(const std::string &name) = 0; + + virtual PropertyList getProperties() const = 0; + virtual void addPropertiesToList( + JSPropertyNameAccumulatorRef propertyNames) const = 0; +}; + +typedef DPL::SharedPtr IPluginManagerPtr; +} +} +} + +#endif // WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ diff --git a/src_wearable/modules/API/PluginManager/PluginManagerFactory.cpp b/src_wearable/modules/API/PluginManager/PluginManagerFactory.cpp new file mode 100644 index 0000000..3866028 --- /dev/null +++ b/src_wearable/modules/API/PluginManager/PluginManagerFactory.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file PluginManagerFactory.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#include "PluginManagerFactory.h" +#include + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +PluginManagerFactory::PluginManagerFactory() +{} + +PluginManagerFactory& PluginManagerFactory::getInstance() +{ + static PluginManagerFactory instance; + return instance; +} + +IPluginManagerPtr PluginManagerFactory::getPluginManager( + int widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context) const +{ + return IPluginManagerPtr( + new PluginManager(widgetHandle, objectUri, object, context)); +} +} +} +} diff --git a/src_wearable/modules/API/PluginManager/PluginManagerFactory.h b/src_wearable/modules/API/PluginManager/PluginManagerFactory.h new file mode 100644 index 0000000..b13a36a --- /dev/null +++ b/src_wearable/modules/API/PluginManager/PluginManagerFactory.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file PluginManagerFactory.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ +#define WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +class PluginManagerFactory : private DPL::Noncopyable +{ + public: + static PluginManagerFactory& getInstance(); + IPluginManagerPtr getPluginManager( + int widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context) const; + + private: + PluginManagerFactory(); +}; +} +} +} + +#endif // WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ diff --git a/src_wearable/modules/API/PluginManager/config.cmake b/src_wearable/modules/API/PluginManager/config.cmake new file mode 100644 index 0000000..f513d08 --- /dev/null +++ b/src_wearable/modules/API/PluginManager/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_PLUGIN_MANAGER_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_PLUGIN_MANAGER + ${CURRENT_PATH}/PluginManagerFactory.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h b/src_wearable/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h new file mode 100644 index 0000000..a001b71 --- /dev/null +++ b/src_wearable/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file ISoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event interfece + */ + +#ifndef WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H +#define WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H + +#include + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +class ISoftKeyboardChangeEvent +{ + public: + virtual std::string getState() const = 0; + virtual int getWidth() const = 0; + virtual int getHeight() const = 0; + + virtual ~ISoftKeyboardChangeEvent() {} +}; + +typedef std::shared_ptr ISoftKeyboardChangeEventPtr; +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis + +#endif // WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H diff --git a/src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp b/src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp new file mode 100644 index 0000000..7cd04ba --- /dev/null +++ b/src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file SoftKeyboardChangeEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event class implementation + */ + +#include "SoftKeyboardChangeEvent.h" + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +SoftKeyboardChangeEvent::SoftKeyboardChangeEvent( + std::string state, int width, int height) : + m_state(state), m_width(width), m_height(height) +{} + +SoftKeyboardChangeEvent::~SoftKeyboardChangeEvent() +{} + +std::string SoftKeyboardChangeEvent::getState() const +{ + return m_state; +} + +int SoftKeyboardChangeEvent::getWidth() const +{ + return m_width; +} + +int SoftKeyboardChangeEvent::getHeight() const +{ + return m_height; +} +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis diff --git a/src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h b/src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h new file mode 100644 index 0000000..df8f721 --- /dev/null +++ b/src_wearable/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file SoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event class + */ + +#ifndef WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H +#define WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H + +#include +#include "ISoftKeyboardChangeEvent.h" + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +class SoftKeyboardChangeEvent : public ISoftKeyboardChangeEvent +{ + public: + explicit SoftKeyboardChangeEvent( + std::string state, + int width, + int height); + ~SoftKeyboardChangeEvent(); + + std::string getState() const; + int getWidth() const; + int getHeight() const; + + private: + std::string m_state; + int m_width; + int m_height; +}; +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis + +#endif // WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H diff --git a/src_wearable/modules/API/SoftKeyboardChangeEvent/config.cmake b/src_wearable/modules/API/SoftKeyboardChangeEvent/config.cmake new file mode 100644 index 0000000..398a39b --- /dev/null +++ b/src_wearable/modules/API/SoftKeyboardChangeEvent/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_SOFTKEYBOARD_CHANGE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_SOFTKEYBOARD_CHANGE_EVENT + ${CURRENT_PATH}/SoftKeyboardChangeEvent.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/API/StorageEvent/IStorageEvent.h b/src_wearable/modules/API/StorageEvent/IStorageEvent.h new file mode 100644 index 0000000..5c34514 --- /dev/null +++ b/src_wearable/modules/API/StorageEvent/IStorageEvent.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file IStorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event interfece + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H +#define WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H + +#include +#include +#include + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +class IStorageEvent +{ + public: + + virtual std::string getKey() const = 0; + virtual DPL::OptionalString getOldValue() const = 0; + virtual DPL::OptionalString getNewValue() const = 0; + virtual std::string getUrl() const = 0; + virtual LocalStorage::Api::ILocalStoragePtr getStorageArea() const = 0; + + virtual void setKey(const std::string &inKey) = 0; + virtual void setOldValue(const std::string &inValue) = 0; + virtual void setNewValue(const std::string &inValue) = 0; + virtual void setUrl(const std::string &inUrl) = 0; + virtual void setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea) = 0; +}; + +typedef DPL::SharedPtr IStorageEventPtr; +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H diff --git a/src_wearable/modules/API/StorageEvent/StorageEvent.cpp b/src_wearable/modules/API/StorageEvent/StorageEvent.cpp new file mode 100644 index 0000000..11068b7 --- /dev/null +++ b/src_wearable/modules/API/StorageEvent/StorageEvent.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEvent.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event class implementation + */ + +#include "StorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +StorageEvent::StorageEvent() : + m_storageArea(NULL) {} + +StorageEvent::StorageEvent( + const LocalStorage::Api::ILocalStoragePtr &storageArea) : + m_storageArea(storageArea) {} + +std::string StorageEvent::getKey() const +{ + return m_key; +} + +DPL::OptionalString StorageEvent::getOldValue() const +{ + return m_oldValue; +} + +DPL::OptionalString StorageEvent::getNewValue() const +{ + return m_newValue; +} +std::string StorageEvent::getUrl() const +{ + return m_url; +} + +LocalStorage::Api::ILocalStoragePtr StorageEvent::getStorageArea() const +{ + return m_storageArea; +} + +void StorageEvent::setKey(const std::string &inKey) +{ + m_key = inKey; +} + +void StorageEvent::setOldValue(const std::string &inValue) +{ + m_oldValue = DPL::FromUTF8String(inValue); +} + +void StorageEvent::setNewValue(const std::string &inValue) +{ + m_newValue = DPL::FromUTF8String(inValue); +} + +void StorageEvent::setUrl(const std::string &inUrl) +{ + m_url = inUrl; +} + +void StorageEvent::setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea) +{ + m_storageArea = inStorageArea; +} +} // Api +} // StorageEvent +} // WrtDeviceApis diff --git a/src_wearable/modules/API/StorageEvent/StorageEvent.h b/src_wearable/modules/API/StorageEvent/StorageEvent.h new file mode 100644 index 0000000..37df421 --- /dev/null +++ b/src_wearable/modules/API/StorageEvent/StorageEvent.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event class + */ + +#ifndef WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H +#define WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H + +#include +#include "IStorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +class StorageEvent : public IStorageEvent +{ + public: + + StorageEvent(); + explicit StorageEvent( + const LocalStorage::Api::ILocalStoragePtr &storageArea); + + std::string getKey() const; + DPL::OptionalString getOldValue() const; + DPL::OptionalString getNewValue() const; + std::string getUrl() const; + LocalStorage::Api::ILocalStoragePtr getStorageArea() const; + + void setKey(const std::string &inKey); + void setOldValue(const std::string &inValue); + void setNewValue(const std::string &inValue); + void setUrl(const std::string &inUrl); + void setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea); + + private: + std::string m_key; + DPL::OptionalString m_oldValue; + DPL::OptionalString m_newValue; + std::string m_url; + LocalStorage::Api::ILocalStoragePtr m_storageArea; +}; +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H diff --git a/src_wearable/modules/API/StorageEvent/StorageEventMgr.cpp b/src_wearable/modules/API/StorageEvent/StorageEventMgr.cpp new file mode 100644 index 0000000..92b8772 --- /dev/null +++ b/src_wearable/modules/API/StorageEvent/StorageEventMgr.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEventMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event getter + */ + +#include "StorageEventMgr.h" +#include "StorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +IStorageEventPtr getStorageEvent() +{ + return IStorageEventPtr(new StorageEvent()); +} +} // Api +} // StorageEvent +} // WrtDeviceApis diff --git a/src_wearable/modules/API/StorageEvent/StorageEventMgr.h b/src_wearable/modules/API/StorageEvent/StorageEventMgr.h new file mode 100644 index 0000000..b519abd --- /dev/null +++ b/src_wearable/modules/API/StorageEvent/StorageEventMgr.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file StorageEventMgr.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event interfece + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H +#define WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H + +#include "IStorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +IStorageEventPtr getStorageEvent(); +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H + diff --git a/src_wearable/modules/API/StorageEvent/config.cmake b/src_wearable/modules/API/StorageEvent/config.cmake new file mode 100644 index 0000000..a0029fc --- /dev/null +++ b/src_wearable/modules/API/StorageEvent/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(API_STORAGE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_STORAGE_EVENT + ${CURRENT_PATH}/StorageEventMgr.cpp + ${CURRENT_PATH}/StorageEvent.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/API/TizenServiceEvent/ITizenServiceEvent.h b/src_wearable/modules/API/TizenServiceEvent/ITizenServiceEvent.h new file mode 100644 index 0000000..8882b69 --- /dev/null +++ b/src_wearable/modules/API/TizenServiceEvent/ITizenServiceEvent.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file ITizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen Service event interfece + */ + +#ifndef _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ +#define _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +class ITizenServiceEvent +{ + public: + virtual float getScale() const = 0; + virtual std::string getBundle() const = 0; + + virtual void setScale(const float scale) = 0; + virtual void setBundle(const std::string &bundle) = 0; + virtual ~ITizenServiceEvent() {} +}; + +typedef DPL::SharedPtr ITizenServiceEventPtr; +} // Api +} // TizenServiceEvent +} // WrtDeviceApis + +#endif // _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ diff --git a/src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.cpp b/src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.cpp new file mode 100644 index 0000000..b6233c6 --- /dev/null +++ b/src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file TizenServiceEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen appservice event class implementation + */ + +#include "TizenServiceEvent.h" + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +TizenServiceEvent::TizenServiceEvent() : + m_scale(0) +{} + +TizenServiceEvent::~TizenServiceEvent() +{} + +float TizenServiceEvent::getScale() const +{ + return m_scale; +} + +std::string TizenServiceEvent::getBundle() const +{ + return m_bundle; +} + +void TizenServiceEvent::setScale(const float scale) +{ + m_scale = scale; +} + +void TizenServiceEvent::setBundle(const std::string& bundle) +{ + m_bundle = bundle; +} +} // Api +} // TizenServiceEvent +} // WrtDeviceApis diff --git a/src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.h b/src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.h new file mode 100644 index 0000000..3b577f0 --- /dev/null +++ b/src_wearable/modules/API/TizenServiceEvent/TizenServiceEvent.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file TizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen Service event class + */ + +#ifndef _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ +#define _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ + +#include +#include "ITizenServiceEvent.h" + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +class TizenServiceEvent : public ITizenServiceEvent +{ + public: + + TizenServiceEvent(); + ~TizenServiceEvent(); + + float getScale() const; + std::string getBundle() const; + + void setScale(const float scale); + void setBundle(const std::string &bundle); + + private: + float m_scale; + std::string m_bundle; +}; +} // Api +} // TizenServiceEvent +} // WrtDeviceApis + +#endif // _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ diff --git a/src_wearable/modules/API/TizenServiceEvent/config.cmake b/src_wearable/modules/API/TizenServiceEvent/config.cmake new file mode 100644 index 0000000..5a64dcd --- /dev/null +++ b/src_wearable/modules/API/TizenServiceEvent/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_TIZEN_SERVICE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_TIZEN_SERVICE_EVENT + ${CURRENT_PATH}/TizenServiceEvent.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/API/Widget/IWidget.h b/src_wearable/modules/API/Widget/IWidget.h new file mode 100644 index 0000000..1936ee9 --- /dev/null +++ b/src_wearable/modules/API/Widget/IWidget.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file IWidget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef INTERFACE_WIDGET_CONFIG_INFO_H +#define INTERFACE_WIDGET_CONFIG_INFO_H + +#include + +#include + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +class IWidget; +typedef DPL::SharedPtr IWidgetPtr; + +class IWidget +{ + public: // methods + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthor() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthorEmail() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthorHref() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getDescription() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getId() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getName() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getShortName() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getVersion() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual unsigned int getHeight() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual unsigned int getWidth() const = 0; + + virtual ~IWidget() + {} +}; +} +} +} + +#endif diff --git a/src_wearable/modules/API/Widget/WidgetFactory.cpp b/src_wearable/modules/API/Widget/WidgetFactory.cpp new file mode 100644 index 0000000..2197a75 --- /dev/null +++ b/src_wearable/modules/API/Widget/WidgetFactory.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file WidgetFactory.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#include "WidgetFactory.h" + +#include + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +IWidgetPtr WidgetFactory::createWidget() +{ + return IWidgetPtr(new WrtDeviceApis::Widget::Widget()); +} +} +} +} diff --git a/src_wearable/modules/API/Widget/WidgetFactory.h b/src_wearable/modules/API/Widget/WidgetFactory.h new file mode 100644 index 0000000..b068dc2 --- /dev/null +++ b/src_wearable/modules/API/Widget/WidgetFactory.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file WidgetFactory.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef _WIDGET_FACTORY_H +#define _WIDGET_FACTORY_H + +#include +#include +#include + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +class WidgetFactory : private DPL::Noncopyable +{ + public: + + /** + * Create widget + * @param[in] id of the widget + */ + static IWidgetPtr createWidget(); + + private: + WidgetFactory() + {} +}; +} +} +} + +#endif diff --git a/src_wearable/modules/API/Widget/config.cmake b/src_wearable/modules/API/Widget/config.cmake new file mode 100644 index 0000000..11ffcc8 --- /dev/null +++ b/src_wearable/modules/API/Widget/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_WIDGET_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_WIDGET + ${CURRENT_PATH}/WidgetFactory.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/API/WidgetDB/IWidgetDB.h b/src_wearable/modules/API/WidgetDB/IWidgetDB.h new file mode 100644 index 0000000..76ff03f --- /dev/null +++ b/src_wearable/modules/API/WidgetDB/IWidgetDB.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IWidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Widget interface to access WRT DB + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_IWIDGETDB_H_ +#define WRTDEVICEAPIS_WIDGETDB_IWIDGETDB_H_ + +#include "IWidgetFeature.h" +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +class IWidgetDB; +typedef DPL::SharedPtr IWidgetDBPtr; + +typedef std::vector Features; + +enum class ConfigAttribute +{ + ID, + VERSION, + DESCRIPTION, + LICENSE, + LICENSE_HREF, + AUTHOR_NAME, + AUTHOR_HREF, + AUTHOR_EMAIL, + NAME, + SHORT_NAME, + ICON, + WIDTH, + HEIGHT, + INSTALL_PATH, + PUBLIC_STORAGE_PATH +}; + +enum class InstallationStatus +{ + STATUS_INSTALLED, + STATUS_LATEST, + STATUS_UNINSTALLED +}; + +class IWidgetDB +{ + public: + + virtual int getWidgetId() const = 0; + + virtual std::string getLanguage() const = 0; + + virtual std::string getConfigValue(ConfigAttribute attribute) const = 0; + + virtual std::string getUserAgent() const = 0; + + virtual InstallationStatus checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const = 0; + + virtual Features getWidgetFeatures() const = 0; + + virtual Features getRegisteredFeatures() const = 0; + + virtual std::string getWidgetInstallationPath() const = 0; + + virtual std::string getWidgetPersistentStoragePath() const = 0; + + virtual std::string getWidgetTemporaryStoragePath() const = 0; + + virtual ~IWidgetDB() + {} +}; +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif + diff --git a/src_wearable/modules/API/WidgetDB/IWidgetFeature.h b/src_wearable/modules/API/WidgetDB/IWidgetFeature.h new file mode 100644 index 0000000..2371c1e --- /dev/null +++ b/src_wearable/modules/API/WidgetDB/IWidgetFeature.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_INTERFACE_H_ +#define WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_INTERFACE_H_ + +#include +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +class IWidgetFeature +{ + public: + + virtual ~IWidgetFeature() + {} + + virtual std::string getName() const = 0; + + virtual bool isRequestedByWidget() const = 0; +}; + +typedef DPL::SharedPtr IWidgetFeaturePtr; +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif diff --git a/src_wearable/modules/API/WidgetDB/WidgetDBMgr.cpp b/src_wearable/modules/API/WidgetDB/WidgetDBMgr.cpp new file mode 100644 index 0000000..b275f33 --- /dev/null +++ b/src_wearable/modules/API/WidgetDB/WidgetDBMgr.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IWidgetDBMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "IWidgetDB.h" +#include "WidgetDBMgr.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +IWidgetDBPtr getWidgetDB(int widgetId) +{ + return IWidgetDBPtr(new WrtDeviceApis::WidgetDB::WidgetDB(widgetId)); +} +} // Api +} // WidgetDB +} // WrtDeviceApis diff --git a/src_wearable/modules/API/WidgetDB/WidgetDBMgr.h b/src_wearable/modules/API/WidgetDB/WidgetDBMgr.h new file mode 100644 index 0000000..6de3f99 --- /dev/null +++ b/src_wearable/modules/API/WidgetDB/WidgetDBMgr.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file IWidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Widget interface to access WRT DB + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H +#define WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H + +#include "IWidgetDB.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +IWidgetDBPtr getWidgetDB(int widgetId); +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H + diff --git a/src_wearable/modules/API/WidgetDB/config.cmake b/src_wearable/modules/API/WidgetDB/config.cmake new file mode 100644 index 0000000..14a6acc --- /dev/null +++ b/src_wearable/modules/API/WidgetDB/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(API_WIDGETDB_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_WIDGETDB + ${CURRENT_PATH}/WidgetDBMgr.cpp + PARENT_SCOPE +) + diff --git a/src_wearable/modules/API/config.cmake b/src_wearable/modules/API/config.cmake new file mode 100644 index 0000000..82b25da --- /dev/null +++ b/src_wearable/modules/API/config.cmake @@ -0,0 +1,3 @@ +include_config_file(Widget) +include_config_file(StorageEvent) +include_config_file(LocalStorage) \ No newline at end of file diff --git a/src_wearable/modules/CMakeLists.txt b/src_wearable/modules/CMakeLists.txt new file mode 100644 index 0000000..85db759 --- /dev/null +++ b/src_wearable/modules/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/${PLATFORM} +) + +add_subdirectory(API) +add_subdirectory(${PLATFORM}) +add_subdirectory(packages) diff --git a/src_wearable/modules/DESCRIPTION b/src_wearable/modules/DESCRIPTION new file mode 100644 index 0000000..a5d1510 --- /dev/null +++ b/src_wearable/modules/DESCRIPTION @@ -0,0 +1 @@ +Platform abstraction diff --git a/src_wearable/modules/packages/CMakeLists.txt b/src_wearable/modules/packages/CMakeLists.txt new file mode 100644 index 0000000..ed3e799 --- /dev/null +++ b/src_wearable/modules/packages/CMakeLists.txt @@ -0,0 +1,34 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set(TARGET_MODULE_FILESYSTEM "wrt-plugins-filesystem") +set(TARGET_MODULE_WIDGET "wrt-plugins-widget") +set(TARGET_MODULE_LOCALSTORAGE "wrt-plugins-localstorage") +set(TARGET_MODULE_WIDGET_INTERFACE "wrt-plugins-widget-interface") +set(TARGET_MODULE_STORAGEEVENT "wrt-plugins-storageevent") +set(TARGET_MODULE_TIZEN_SERVICE_EVENT "wrt-plugins-tizen-service-event") +set(TARGET_MODULE_SOFTKEYBOARD_CHANGE_EVENT "wrt-plugins-softkeyboardchange-event") +set(TARGET_MODULE_WIDGETDB "wrt-plugins-widgetdb") +set(TARGET_MODULE_PLUGIN_MANAGER "wrt-plugins-plugin-manager") + +add_subdirectory(Filesystem) +add_subdirectory(Widget) +add_subdirectory(LocalStorage) +add_subdirectory(WidgetInterface) +add_subdirectory(WidgetDB) +add_subdirectory(PluginManager) +add_subdirectory(StorageEvent) +add_subdirectory(TizenServiceEvent) +add_subdirectory(SoftKeyboardChangeEvent) diff --git a/src_wearable/modules/packages/Filesystem/CMakeLists.txt b/src_wearable/modules/packages/Filesystem/CMakeLists.txt new file mode 100644 index 0000000..e5079dc --- /dev/null +++ b/src_wearable/modules/packages/Filesystem/CMakeLists.txt @@ -0,0 +1,54 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_FILESYSTEM_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/Filesystem) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_FILESYSTEM}) + +set(SRCS + ${SRCS_API_FILESYSTEM} + ${SRCS_PLATFORM_IMPLEMENTATION_FILESYSTEM} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(IManager.h) +install_header_file(INode.h) +install_header_file(INodeTypes.h) +install_header_file(IPath.h) +install_header_file(IStream.h) +install_header_file(EventResolve.h) +install_header_file(EventCopy.h) +install_header_file(EventMove.h) +install_header_file(EventRemove.h) +install_header_file(EventFind.h) +install_header_file(EventListNodes.h) +install_header_file(EventOpen.h) +install_header_file(EventReadText.h) +install_header_file(Enums.h) +install_header_file(NodeFilter.h) diff --git a/src_wearable/modules/packages/LocalStorage/CMakeLists.txt b/src_wearable/modules/packages/LocalStorage/CMakeLists.txt new file mode 100644 index 0000000..90d648a --- /dev/null +++ b/src_wearable/modules/packages/LocalStorage/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +set(TARGET_NAME ${TARGET_MODULE_LOCALSTORAGE}) + +set(SRCS + ${SRCS_API_LOCALSTORAGE} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${TARGET_MODULE_WIDGET_INTERFACE} +) + diff --git a/src_wearable/modules/packages/PluginManager/CMakeLists.txt b/src_wearable/modules/packages/PluginManager/CMakeLists.txt new file mode 100644 index 0000000..a66bbfd --- /dev/null +++ b/src_wearable/modules/packages/PluginManager/CMakeLists.txt @@ -0,0 +1,58 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# + +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_PLUGIN_MANAGER_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/PluginManager) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_PLUGIN_MANAGER}) + +pkg_search_module(webkit2 REQUIRED ewebkit2) + +include_directories( + ${INCLUDES_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} + ${webkit2_INCLUDE_DIRS}} +) + +set(SRCS + ${SRCS_API_PLUGIN_MANAGER} + ${SRCS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_PLUGIN_LOADING_LIB} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} + ${LIBS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} +) + +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(PluginManagerFactory.h) +install_header_file(IPluginManager.h) diff --git a/src_wearable/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt b/src_wearable/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt new file mode 100644 index 0000000..84b9944 --- /dev/null +++ b/src_wearable/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 0.1 + +set(TARGET_NAME ${TARGET_MODULE_SOFTKEYBOARD_CHANGE_EVENT}) + +set(SRCS + ${SRCS_API_SOFTKEYBOARD_CHANGE_EVENT} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) diff --git a/src_wearable/modules/packages/StorageEvent/CMakeLists.txt b/src_wearable/modules/packages/StorageEvent/CMakeLists.txt new file mode 100644 index 0000000..dc9ff0d --- /dev/null +++ b/src_wearable/modules/packages/StorageEvent/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +set(TARGET_NAME ${TARGET_MODULE_STORAGEEVENT}) + +set(SRCS + ${SRCS_API_STORAGE_EVENT} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${TARGET_MODULE_LOCALSTORAGE} +) + diff --git a/src_wearable/modules/packages/TizenServiceEvent/CMakeLists.txt b/src_wearable/modules/packages/TizenServiceEvent/CMakeLists.txt new file mode 100644 index 0000000..e8efc16 --- /dev/null +++ b/src_wearable/modules/packages/TizenServiceEvent/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 0.1 + +set(TARGET_NAME ${TARGET_MODULE_TIZEN_SERVICE_EVENT}) + +set(SRCS + ${SRCS_API_TIZEN_SERVICE_EVENT} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) diff --git a/src_wearable/modules/packages/Widget/CMakeLists.txt b/src_wearable/modules/packages/Widget/CMakeLists.txt new file mode 100644 index 0000000..74bf1a6 --- /dev/null +++ b/src_wearable/modules/packages/Widget/CMakeLists.txt @@ -0,0 +1,30 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set(TARGET_NAME ${TARGET_MODULE_WIDGET}) + +set(SRCS + ${SRCS_API_WIDGET} + ${SRCS_IMPLEMENTATION_WIDGET} +) + +add_library(${TARGET_NAME} STATIC ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${TARGET_MODULE_WIDGETDB} +) + diff --git a/src_wearable/modules/packages/WidgetDB/CMakeLists.txt b/src_wearable/modules/packages/WidgetDB/CMakeLists.txt new file mode 100644 index 0000000..ec91fdb --- /dev/null +++ b/src_wearable/modules/packages/WidgetDB/CMakeLists.txt @@ -0,0 +1,50 @@ +# +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_WIDGETDB_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/WidgetDB) +endmacro() + +set(TARGET_NAME ${TARGET_MODULE_WIDGETDB}) + +include_directories( + ${INCLUDES_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +set(SRCS + ${SRCS_API_WIDGETDB} + ${SRCS_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${LIBS_PLATFORM_IMPLEMENTATION_WIDGETDB} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(IWidgetDB.h) +install_header_file(IWidgetFeature.h) +install_header_file(WidgetDBMgr.h) + diff --git a/src_wearable/modules/packages/WidgetInterface/CMakeLists.txt b/src_wearable/modules/packages/WidgetInterface/CMakeLists.txt new file mode 100644 index 0000000..0ebb5e2 --- /dev/null +++ b/src_wearable/modules/packages/WidgetInterface/CMakeLists.txt @@ -0,0 +1,50 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +macro(install_header_file HEADER_FILE) + INSTALL(FILES ${API_WIDGET_INTERFACE_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/WidgetInterface) +endmacro() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(wrt-commons-widget-interface-dao REQUIRED wrt-commons-widget-interface-dao) + +include_directories( + ${WIDGET_INTERFACE_INCLUDE_DIRS} + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${wrt-commons-widget-interface-dao_INCLUDE_DIRS}) + +set(TARGET_NAME ${TARGET_MODULE_WIDGET_INTERFACE}) + +set(SRCS + ${SRCS_WIDGET_INTERFACE} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMONS} + ${dpl-wrt-dao-ro_LIBRARIES} + ${wrt-commons-widget-interface-dao_LIBRARIES} +) +set_target_properties(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION + ${DESTINATION_LIB_PREFIX}) + +install_header_file(WidgetInterface.h) diff --git a/src_wearable/modules/tizen/CMakeLists.txt b/src_wearable/modules/tizen/CMakeLists.txt new file mode 100644 index 0000000..3cfc293 --- /dev/null +++ b/src_wearable/modules/tizen/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +############################################################################### +# In this section please add modules that shouldn't be visible directly +# beyond wac/ subdirectory, i.e. platform wrappers specific for wac - +# - used only as helpers in AL for wac platform implementation. VConf +# is a good example, its used i.e. in Power/Battery. Unfortunately order in +# in which this modules and AL modules are included is significant, i.e. VConf +# needs to be included before Power as there are some CMake variables set that +# are used in Power config.cmake file. +################################################################################ + +include_config_file(Filesystem) +include_config_file(Widget) +include_config_file(LocalStorage) +include_config_file(WidgetInterface) +add_subdirectory(WidgetInterface) +include_config_file(WidgetDB) +include_config_file(PluginManager) diff --git a/src_wearable/modules/tizen/DESCRIPTION b/src_wearable/modules/tizen/DESCRIPTION new file mode 100644 index 0000000..45900ba --- /dev/null +++ b/src_wearable/modules/tizen/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +API implementation for tizen platform diff --git a/src_wearable/modules/tizen/Filesystem/Manager.cpp b/src_wearable/modules/tizen/Filesystem/Manager.cpp new file mode 100644 index 0000000..750a214 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Manager.cpp @@ -0,0 +1,623 @@ +/* + * 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 "Manager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Node.h" +#include "Utils.h" + +namespace { +const char* PATH_ROOT = "/opt/media"; +const char* PATH_DOWNLOADS = "/opt/media/Downloads"; +const char* PATH_DOCUMENTS = "/opt/media/Documents"; +const char* PATH_SOUNDS = "/opt/media/Music"; +const char* PATH_IMAGES = "/opt/media/Images"; +const char* PATH_VIDEOS = "/opt/media/Videos"; +const char* PATH_SDCARD = "/opt/storage/sdcard"; +} + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +Manager::Locations Manager::m_locations; +const std::size_t Manager::m_maxPathLength = 256; +NodeList Manager::m_openedNodes; + +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."); +} + +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 +{ + Assert(path); + NodeListIterator it = m_openedNodes.begin(); + for (; it != m_openedNodes.end(); ++it) { + Assert(*it); + if (*path == *(*it)->getPath()) { + return true; + } + } + return false; +} + +Manager::Manager() +{ + static bool initialized = init(); + (void) initialized; +} + +Manager::~Manager() +{} + +IPathPtr Manager::getBasePath() const +{ + Locations::const_iterator it = m_locations.find(LT_ROOT); + 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(type); + 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; + Locations::const_iterator it = m_locations.begin(); + for (; it != m_locations.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +void Manager::getNode(const EventResolvePtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +std::size_t Manager::getMaxPathLength() const +{ + return m_maxPathLength; +} + +void Manager::copy(const EventCopyPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::move(const EventMovePtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::remove(const EventRemovePtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::find(const EventFindPtr& event) +{ + EventRequestReceiver::PostRequest(event); +} + +void Manager::find(const IPathPtr& path, + const FiltersMap& filters, + NodeList& result, + const EventFindPtr& event) +{ + Try { + AssertMsg(path, "path is NULL"); + FTS *fts; + FTSENT *ftsent; + std::string pth = path->getFullPath(); + char * const paths[] = { const_cast(pth.c_str()), NULL }; + + if ((fts = + fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) + { + //ERROR + int error = errno; + LogError(__PRETTY_FUNCTION__ << ": fts_open on " + << pth + << " failed with error: " + << strerror(error)); + return; + } + + while ((ftsent = fts_read(fts)) != NULL) { + if (event && event->checkCancelled()) { + break; + } + switch (ftsent->fts_info) { + case FTS_DP: + //directory in postorder - do nothing + break; + case FTS_D: + case FTS_DC: + case FTS_F: + case FTS_SL: + case FTS_SLNONE: + case FTS_DEFAULT: + //regular files, symbolic links, directories in preorder + //and other file entries that can be processed further + if (matchFilters(ftsent->fts_name, *ftsent->fts_statp, + filters)) + { + IPathPtr childPath = IPath::create(ftsent->fts_path); + result.push_back(Node::resolve(childPath)); + } + break; + case FTS_NS: + case FTS_NSOK: + case FTS_DOT: + case FTS_DNR: + case FTS_ERR: + default: + LogWarning(__PRETTY_FUNCTION__ + << ": traversal failed with error: " + << strerror(ftsent->fts_errno)); + ThrowMsg(Commons::PlatformException, + "Error reading directory"); + } + } + + if (fts_close(fts) == -1) { + int error = errno; + LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: " + << strerror(error)); + ThrowMsg(Commons::PlatformException, + "Could not close platform node."); + } + } + Catch(Commons::Exception) {} +} + +void Manager::copyElement( + const std::string &src, const std::string &dest, bool recursive) const +{ + LogDebug("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_mkdir(dest.c_str())) { + LogDebug("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(data)).c_str(), + (dest + '/' + static_cast(data)).c_str()); + } + Catch(Commons::PlatformException) + { + //remove rest of the list + EINA_LIST_FREE(list, data) + { + free(data); + } + 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); +} + +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(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 { + event->setResult(Node::resolve(event->getPath())); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + event->setCancelAllowed(true); +} + +void Manager::checkPaths( + Api::IPathPtr &src, + Api::IPathPtr &dest) +{ + Assert(dest); + Assert(src); + if (!dest->isAbsolute()) { + dest = src->getPath() + *dest; + } + + if (src == dest) { + ThrowMsg(Commons::PlatformException, + "Destination is same as source: " << src->getFullPath()); + } + + INodePtr parent; + Try { + parent = Node::resolve(IPath::create(dest->getPath())); + } + Catch(Commons::PlatformException) { + 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."); + } + + if (!access(parent->getPath(), AT_WRITE)) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to write to destination."); + } +} + +bool Manager::pathExists(const std::string &path) +{ + errno = 0; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(path.c_str(), &info); + if ((status != 0) && (errno != ENOENT)) { + ThrowMsg(Commons::PlatformException, + "No access to platform destination node."); + } + return 0 == status; +} + +void Manager::OnRequestReceived(const EventCopyPtr& event) +{ + Try { + INodePtr srcNode = Node::resolve(event->getSource()); + int requiredAccess; + switch (srcNode->getType()) { + case NT_DIRECTORY: + requiredAccess = AT_EXEC; + break; + case NT_FILE: + requiredAccess = AT_READ; + break; + } + if (!access(srcNode->getPath(), requiredAccess)) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to copy source node."); + } + + IPathPtr src = event->getSource(); + IPathPtr dest = event->getDestination(); + + checkPaths(src, dest); + + std::string realSrc = src->getFullPath(); + std::string realDest = dest->getFullPath(); + + if (pathExists(realDest)) { + //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(event->getDestination()); + node->remove(event->getOptions()); + } + Catch(Commons::PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + event->setExceptionCode( + Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode( + Commons::ExceptionCodes::SecurityException); + } + } + //Destination is not exist. Start copy now. + copyElement(realSrc, realDest); + + event->setResult(Node::resolve(dest)); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + //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); + if (!access(srcNode->getParent()->getPath(), AT_WRITE)) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to move source node."); + } + + checkPaths(src, dest); + + bool destExists = pathExists(dest->getFullPath()); + + if (destExists && (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; + if (0 != ::rename(src->getFullPath().c_str(), + dest->getFullPath().c_str())) + { + int error = errno; + switch (error) { + case EXDEV: + { + if (destExists) { + //destination exist. Need to be removed + Try { + INodePtr node = Node::resolve( + event->getDestination()); + node->remove(event->getOptions()); + } + Catch(Commons::PlatformException) { + LogError("Exception while removing dest directory"); + event->setExceptionCode( + Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode( + Commons::ExceptionCodes::SecurityException); + } + } + + copyElement(src->getFullPath(), + dest->getFullPath()); + //remove source files + Try { + INodePtr node = Node::resolve(event->getSource()); + node->remove(event->getOptions()); + } + Catch(Commons::Exception) { + LogError("Exception: " + << _rethrown_exception.GetMessage()); + } + break; + } + default: + ThrowMsg(Commons::PlatformException, + "Error on rename: " << DPL::GetErrnoString(error)); + break; + } + } + + event->setResult(Node::resolve(dest)); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + event->setCancelAllowed(false); +} + +void Manager::OnRequestReceived(const EventRemovePtr& event) +{ + if (!event->checkCancelled()) { + Try { + INodePtr node = Node::resolve(event->getPath()); + node->remove(event->getOptions()); + } + Catch(Commons::PlatformException) { + LogError("Exception: " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + 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) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + event->setCancelAllowed(true); +} + +bool Manager::init() +{ + m_locations[LT_ROOT] = IPath::create(PATH_ROOT); + m_locations[LT_SDCARD] = IPath::create(PATH_SDCARD); + setupLocation(LT_DOWNLOADS, PATH_DOWNLOADS); + setupLocation(LT_DOCUMENTS, PATH_DOCUMENTS); + setupLocation(LT_SOUNDS, PATH_SOUNDS); + setupLocation(LT_IMAGES, PATH_IMAGES); + setupLocation(LT_VIDEOS, PATH_VIDEOS); + + return true; +} + +void Manager::setupLocation(LocationType location, + const char* path) +{ + if (!nodeExists(path)) { + try { + makePath(path, 0755); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.DumpToString()); + return; + } + } + m_locations[location] = IPath::create(path); +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/Filesystem/Manager.h b/src_wearable/modules/tizen/Filesystem/Manager.h new file mode 100644 index 0000000..fa59e3d --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Manager.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_MANAGER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include "Node.h" +#include "Path.h" + +namespace WrtDeviceApis { +namespace Filesystem { +class Manager : public Api::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); + + public: + Manager(); + ~Manager(); + + Api::IPathPtr getBasePath() const; + + Api::IPathPtr getLocationPath(Api::LocationType type) const; + + Api::LocationPaths getLocationPaths() const; + + Api::LocationTypes getLocations() const; + + void getNode(const Api::EventResolvePtr& event); + + std::size_t getMaxPathLength() const; + + void copy(const Api::EventCopyPtr& event); + + void move(const Api::EventMovePtr& event); + + void remove(const Api::EventRemovePtr& event); + + void find(const Api::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 Api::IPathPtr& path, + const Api::FiltersMap& filter, + Api::NodeList& result, + const Api::EventFindPtr& event = Api::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 Api::IPathPtr& path, + int accessType) const; + + void addOpenedNode(const Api::INodePtr& node); + void removeOpenedNode(const Api::INodePtr& node); + bool checkIfOpened(const Api::IPathPtr& path) const; + + protected: + bool matchFilters(const std::string& name, + const struct stat& info, + const Api::FiltersMap& filter); + + void OnRequestReceived(const Api::EventResolvePtr& event); + void OnRequestReceived(const Api::EventCopyPtr& event); + void OnRequestReceived(const Api::EventMovePtr& event); + void OnRequestReceived(const Api::EventRemovePtr& event); + void OnRequestReceived(const Api::EventFindPtr& event); + + private: + typedef std::map Locations; + + private: + /** + * Initializes statics of Manager class. + * Used only internally. + * @return True on success, false otherwsie. + */ + static bool init(); + + static void setupLocation(Api::LocationType location, + const char* path); + + void copyElement(const std::string &src, + const std::string &dest, + bool recursive = true) const; + + /** + * Check two paths to copy/move. Checks if they are not the same and + * required permissions. + * @param src + * @param dest + */ + void checkPaths(Api::IPathPtr &src, Api::IPathPtr &dest); + bool pathExists(const std::string &path); + + private: + static Locations m_locations; ///< Paths to default locations. + static const std::size_t m_maxPathLength; ///< Maximum path length. + static Api::NodeList m_openedNodes; ///< List of nodes that has opened + // streams. +}; +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_MANAGER_H_ diff --git a/src_wearable/modules/tizen/Filesystem/Node.cpp b/src_wearable/modules/tizen/Filesystem/Node.cpp new file mode 100644 index 0000000..221285c --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Node.cpp @@ -0,0 +1,608 @@ +/* + * 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 "Node.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Manager.h" +#include "NodeFilterMatcher.h" + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +INodePtr Node::resolve(const IPathPtr& path) +{ + struct stat info; + if (lstat(path->getFullPath().c_str(), &info) != 0) { + LogError("File: " << path->getFullPath().c_str()); + ThrowMsg(Commons::PlatformException, + "Node does not exist or access denied."); + } + + if (!S_ISDIR(info.st_mode) && !S_ISREG(info.st_mode)) { + ThrowMsg(Commons::PlatformException, + "Platform node is of unsupported type."); + } + + NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; + NodePtr result(new Node(path, type)); + return DPL::StaticPointerCast(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; + int return_code; + struct dirent entry; + struct dirent *entry_result; + for (return_code = readdir_r(dir, &entry, &entry_result); + entry_result != NULL && return_code == 0; + return_code = readdir_r(dir, &entry, &entry_result)) { + if (!strncmp(entry.d_name, ".", 1) || + !strncmp(entry.d_name, "..", 2)) + { + continue; + } + result.push_back(entry.d_name); + } + if (return_code != 0 || 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; + int return_code; + struct dirent entry; + struct dirent *entry_result; + for (return_code = readdir_r(dir, &entry, &entry_result); + entry_result != NULL && return_code == 0; + return_code = readdir_r(dir, &entry, &entry_result)) { + if (!strncmp(entry.d_name, ".", 1) || + !strncmp(entry.d_name, "..", 2)) + { + continue; + } + Try { + Assert(m_path); + 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(Commons::PlatformException) {} + } + + if (return_code != 0 || 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) +{ + LogDebug("ENTER"); + EventRequestReceiver::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."); + } + + Assert(m_path); + Assert(path); + 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(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( + SharedFromThis())); + return DPL::StaticPointerCast(stream); +} + +void Node::open(const EventOpenPtr& event) +{ + LogDebug("ENTER"); + EventRequestReceiver::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; + } +} + +std::size_t 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) { + Assert(*it); + Assert(m_path); + 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) +{ + LogDebug("ENTER"); + EventRequestReceiver::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( + 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) || ((status != 0) && (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) + { + LogError("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 */) +{ + LogDebug("ENTER"); + createAsFileInternal(path); + return new Node(path, NT_FILE); +} + +void Node::createAsFileInternal(const IPathPtr& path) +{ + LogDebug("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) +{ + Assert(path); + if (recursive) { + FTS *fts; + FTSENT *ftsent; + int error = 0; + std::string pth = path->getFullPath(); + char * const paths[] = { const_cast(pth.c_str()), NULL }; + + if ((fts = + fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) + { + //ERROR + error = errno; + LogError(__PRETTY_FUNCTION__ << ": fts_open on " + << pth + << " failed with error: " + << strerror(error)); + ThrowMsg(Commons::PlatformException, "Failed to traverse Node"); + } + + while ((ftsent = fts_read(fts)) != NULL) { + switch (ftsent->fts_info) { + case FTS_D: + //directory in preorder - do nothing + break; + case FTS_DP: + //directory in postorder - remove + errno = 0; + if (rmdir(ftsent->fts_accpath) != 0) { + if (errno == EEXIST) { + ThrowMsg(Commons::PlatformException, + "Node has child nodes."); + } + ThrowMsg(Commons::PlatformException, + "Error while removing platform node."); + } + break; + case FTS_DC: + case FTS_F: + case FTS_NSOK: + case FTS_SL: + case FTS_SLNONE: + case FTS_DEFAULT: + { + //regular files and other objects that can safely be removed + IPathPtr file_path = IPath::create(ftsent->fts_path); + removeAsFile(file_path); + break; + } + case FTS_NS: + case FTS_DOT: + case FTS_DNR: + case FTS_ERR: + default: + LogWarning(__PRETTY_FUNCTION__ + << ": traversal failed with error: " + << strerror(ftsent->fts_errno)); + break; + } + } + + if (fts_close(fts) == -1) { + error = errno; + LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: " + << strerror(error)); + } + } else { + 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::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } +} + +void Node::OnRequestReceived(const EventOpenPtr& event) +{ + if (!event->checkCancelled()) { + try { + IStreamPtr result = open(event->getMode()); + event->setResult(result); + } catch (const Commons::PlatformException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } catch (const Commons::SecurityException& ex) { + LogError("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + //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()); + LogDebug("LEAVIN GRACEFULLY"); + } + Catch(Commons::PlatformException) { + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + Catch(Commons::SecurityException) { + event->setExceptionCode(Commons::ExceptionCodes::SecurityException); + } + //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(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(); +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/Filesystem/Node.h b/src_wearable/modules/tizen/Filesystem/Node.h new file mode 100644 index 0000000..de95317 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Node.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_NODE_H_ +#define WRTDEVICEAPIS_FILESYSTEM_NODE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "Path.h" +#include "Stream.h" + +namespace WrtDeviceApis { +namespace Filesystem { +class Node : + public Api::INode, + public DPL::EnableSharedFromThis +{ + public: + static Api::INodePtr resolve(const Api::IPathPtr& path); + + public: + Api::IPathPtr getPath() const; + Api::NodeType getType() const; + int getPermissions() const; + void setPermissions(int perms); + std::size_t getSize() const; + std::time_t getCreated() const; + std::time_t getModified() const; + Api::INodePtr getParent() const; + int getMode() const; + + Api::INodePtr getChild(const Api::IPathPtr& path); + NameList getChildNames() const; + Api::NodeList getChildNodes( + const Api::NodeFilterPtr& filter = Api::NodeFilterPtr()) const; + void getChildNodes(const Api::EventListNodesPtr& event); + Api::INodePtr createChild(const Api::IPathPtr & path, + Api::NodeType, + int options); + Api::IStreamPtr open(int mode); + void open(const Api::EventOpenPtr& event); + void remove(int options); + void read(const Api::EventReadTextPtr& event); + + void onStreamClose(const StreamPtr& stream); + + private: + typedef std::set StreamList; + + private: + static bool exists(const Api::IPathPtr& path); + static struct stat stat(const Api::IPathPtr& path); + + private: + Node(const Api::IPathPtr& path, Api::NodeType type); + + Node* createAsFile(const Api::IPathPtr& path, + int options); + void createAsFileInternal(const Api::IPathPtr& path); + + Node* createAsDirectory(const Api::IPathPtr& path, + int options); + void createAsDirectoryInternal(const Api::IPathPtr& path); + + void removeAsFile(const Api::IPathPtr& path); + void removeAsDirectory(const Api::IPathPtr& path, + bool recursive); + + void OnRequestReceived(const Api::EventListNodesPtr& event); + void OnRequestReceived(const Api::EventOpenPtr& event); + + void OnRequestReceived(const Api::EventReadTextPtr& event); + std::string readText(); + + std::string toUri(int widgetId) const; + + private: + Api::IPathPtr m_path; + Api::NodeType m_type; + int m_perms; + StreamList m_openStreams; + mutable DPL::Mutex m_openStreamsMutex; +}; + +typedef DPL::SharedPtr NodePtr; +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_NODE_H_ */ diff --git a/src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.cpp b/src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.cpp new file mode 100644 index 0000000..a464a69 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "NodeFilterMatcher.h" + +#include + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +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) { + return pcrecpp::RE(*filter).PartialMatch(value); + } + return true; +} + +template +bool NodeFilterMatcher::matchRange(const Type& value, + const boost::optional& min, + const boost::optional& max) +{ + if ((!!min && (value < *min)) || + (!!max && (value > *max))) + { + return false; + } + return true; +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.h b/src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.h new file mode 100644 index 0000000..c69b330 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/NodeFilterMatcher.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ +#define WRTDEVICEAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +class NodeFilterMatcher +{ + public: + static bool match(const Api::INodePtr& value, + const Api::NodeFilterPtr& filter); + + private: + static bool matchString(const std::string& value, + const Api::OptionalString& filter); + + template + static bool matchRange(const Type& value, + const boost::optional& min, + const boost::optional& max); + + private: + NodeFilterMatcher(); +}; +} // Filesystem +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ diff --git a/src_wearable/modules/tizen/Filesystem/Path.cpp b/src_wearable/modules/tizen/Filesystem/Path.cpp new file mode 100644 index 0000000..9aa1197 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Path.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Path.h" + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +const Path::SeparatorType Path::m_pathSeparator = '/'; + +IPathPtr Path::create(const std::string& path) +{ + DPL::SharedPtr result(new Path()); + result->reset(path); + return DPL::StaticPointerCast(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(SharedFromThis()); +} + +IPathPtr Path::append(const IPathPtr& path) +{ + reset(m_fullPath + m_pathSeparator + path->getFullPath()); + return DPL::StaticPointerCast(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)) { + ThrowMsg(Commons::InvalidArgumentException, + "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 +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/Filesystem/Path.h b/src_wearable/modules/tizen/Filesystem/Path.h new file mode 100644 index 0000000..6c7b314 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Path.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_PATH_H_ +#define WRTDEVICEAPIS_FILESYSTEM_PATH_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +class Path : public Api::IPath, + public DPL::EnableSharedFromThis +{ + public: + static Api::IPathPtr create(const std::string& path); + static Api::IPath::SeparatorType getSeparator(); + + public: + std::string getFullPath() const; + std::string getPath() const; + std::string getName() const; + Api::IPathPtr append(const std::string& path); + Api::IPathPtr append(const Api::IPathPtr& path); + bool isAbsolute() const; + Api::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 +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_PATH_H_ */ diff --git a/src_wearable/modules/tizen/Filesystem/Stream.cpp b/src_wearable/modules/tizen/Filesystem/Stream.cpp new file mode 100644 index 0000000..dabc8a0 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Stream.cpp @@ -0,0 +1,302 @@ +/* + * 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 "Stream.h" +#include +#include +#include +#include +#include +#include "Manager.h" +#include "Node.h" + +namespace WrtDeviceApis { +namespace Filesystem { +using namespace Api; + +Stream::Stream(const NodePtr& parent, + int mode) : + m_parent(parent), + m_mode(mode) +{ + AssertMsg(m_parent, "Stream needs to have parent."); + + 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); +} + +char* Stream::getChars(std::size_t num) +{ + checkForReading(); + + std::size_t maxChars = num + 1; + DPL::ScopedArray result; + Try { + result.Reset(new char[maxChars]); + } + Catch(std::bad_alloc) { + ThrowMsg(Commons::PlatformException, "Couldn't allocate output buffer."); + } + if (m_stream.get(result.Get(), maxChars).bad()) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return result.Release(); +} + +unsigned char* Stream::getBytes(std::size_t num) +{ + checkForReading(); + + DPL::ScopedArray 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(static_cast(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(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(Commons::PlatformException, "Could not set position."); + } +} + +long Stream::getSize() const +{ + std::fstream::streampos pos = m_stream.tellg(); + if (pos == -1) { + return -1; + } + + if (!m_stream.seekg(0, std::_S_end)) { + return -1; + } + + long result = m_stream.tellg(); + m_stream.seekg(pos, std::_S_beg); + + return (result == -1 ? result : result + 1); +} + +template +IStreamPtr Stream::write_(T arg) +{ + checkForWriting(); + + if (!(m_stream << arg)) { + LogError("Error while writing to the stream."); + ThrowMsg(Commons::PlatformException, + "Error while writing to the stream."); + } + m_stream.flush(); + + return DPL::StaticPointerCast(SharedFromThis()); +} + +template +IStreamPtr Stream::read_(T& arg) +{ + checkForReading(); + + if (!(m_stream >> arg)) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return DPL::StaticPointerCast(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()) { + LogError("Stream is closed."); + ThrowMsg(Commons::PlatformException, "Stream is closed."); + } + + if (!isWriteable()) { + LogError("Stream is not writeable."); + ThrowMsg(Commons::PlatformException, "Stream is not writeable."); + } +} +} // Filesystem +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/Filesystem/Stream.h b/src_wearable/modules/tizen/Filesystem/Stream.h new file mode 100644 index 0000000..777168f --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Stream.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef WRTDEVICEAPIS_FILESYSTEM_STREAM_H_ +#define WRTDEVICEAPIS_FILESYSTEM_STREAM_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +class Node; +typedef DPL::SharedPtr NodePtr; + +class Stream : + public Api::IStream, + public DPL::EnableSharedFromThis +{ + friend class Node; + + public: + ~Stream(); + + Api::IStreamPtr write(bool arg); + Api::IStreamPtr write(unsigned char arg); + Api::IStreamPtr write(char arg); + Api::IStreamPtr write(int arg); + Api::IStreamPtr write(double arg); + Api::IStreamPtr write(const std::string& arg); + + Api::IStreamPtr read(bool& arg); + Api::IStreamPtr read(unsigned char& arg); + Api::IStreamPtr read(char& arg); + Api::IStreamPtr read(int& arg); + Api::IStreamPtr read(double& arg); + Api::IStreamPtr read(std::string& arg); + + /** + * @throw PlatformException If unable to read from the stream. + */ + unsigned char* getBytes(std::size_t num); + + std::size_t getCount() const; + + /** + * @throw PlatformException If unable to read from the stream. + */ + 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; + + long getSize() const; + + private: + template + Api::IStreamPtr read_(T& arg); + template + Api::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; +}; + +typedef DPL::SharedPtr StreamPtr; +} // Filesystem +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_FILESYSTEM_STREAM_H_ */ diff --git a/src_wearable/modules/tizen/Filesystem/Utils.cpp b/src_wearable/modules/tizen/Filesystem/Utils.cpp new file mode 100644 index 0000000..fc9cde0 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Utils.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Utils.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + */ + +#include +#include +#include +#include +#include +#include +#include "Utils.h" + +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 WrtDeviceApis { +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/src_wearable/modules/tizen/Filesystem/Utils.h b/src_wearable/modules/tizen/Filesystem/Utils.h new file mode 100644 index 0000000..2b1eeb3 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/Utils.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Utils.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + */ + +#ifndef WRTDEVICEAPIS_FILESYSTEM_UTILS_H_ +#define WRTDEVICEAPIS_FILESYSTEM_UTILS_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Filesystem { +bool nodeExists(const std::string& path); + +void makePath(const std::string& path, mode_t mode); +} +} + +#endif diff --git a/src_wearable/modules/tizen/Filesystem/config.cmake b/src_wearable/modules/tizen/Filesystem/config.cmake new file mode 100644 index 0000000..ed22f05 --- /dev/null +++ b/src_wearable/modules/tizen/Filesystem/config.cmake @@ -0,0 +1,26 @@ +get_current_path() + +pkg_search_module(pcrecpp REQUIRED libpcrecpp + ecore REQUIRED ecore-1) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_FILESYSTEM + ${pcrecpp_INCLUDE_DIRS} + ${ecore_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_FILESYSTEM + ${pcrecpp_LIBRARIES} + ${ecore_LIBRARIES} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_FILESYSTEM + ${CURRENT_PATH}/Manager.cpp + ${CURRENT_PATH}/Node.cpp + ${CURRENT_PATH}/Path.cpp + ${CURRENT_PATH}/Stream.cpp + ${CURRENT_PATH}/NodeFilterMatcher.cpp + ${CURRENT_PATH}/Utils.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/tizen/PluginManager/PluginManager.cpp b/src_wearable/modules/tizen/PluginManager/PluginManager.cpp new file mode 100644 index 0000000..8e528b1 --- /dev/null +++ b/src_wearable/modules/tizen/PluginManager/PluginManager.cpp @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file PluginManager.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include "PluginManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace { +const string GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; +const char* SEPARATOR = "."; +} + +namespace WrtDeviceApis { +namespace PluginManager { +PluginManager::PluginManager(int widgetHandle, + const string &objectUri, + JSObjectRef object, + JSContextRef context) : + m_widgetHandle(widgetHandle), + m_objectInstance(object), + m_objectUri(GLOBAL_OBJECT_NAME), + m_shortUri(objectUri), + m_context(context) +{ + m_objectUri.append(SEPARATOR).append(objectUri); + WrtDB::WrtDatabase::attachToThreadRO(); +} + +PluginManager::~PluginManager() +{ + ObjectList::iterator it = m_objectList.begin(); + for (; it != m_objectList.end(); ++it) { + JSValueUnprotect(m_context, it->second); + } + WrtDB::WrtDatabase::detachFromThread(); +} + +bool PluginManager::hasChild(const string &name) const +{ + const PropertyList &prop = getProperties(); + return prop.end() != find(prop.begin(), prop.end(), name); +} + +bool PluginManager::loadChild(const string &name) const +{ + _D("loading %s", name.c_str()); + string localUri = m_objectUri; + localUri.append(SEPARATOR).append(name); + + WrtDB::DbPluginHandle handle = + WrtDB::PluginDAOReadOnly::getPluginHandleForImplementedObject(localUri); + if (handle == WrtDB::INVALID_PLUGIN_HANDLE) { + _E("Plugin not found"); + return false; + } + + WrtDB::DbWidgetFeatureSet features; + WrtDB::WidgetType widgetType; + Try + { + WrtDB::WidgetDAOReadOnly dao(m_widgetHandle); + features = dao.getFeaturesList(); + widgetType = dao.getWidgetType(); + } + Catch(WrtDB::WidgetDAOReadOnly::Exception::Base) + { + // Error while reading database - widget handle may + // be invalid or some data may be missing in database + _E("Cannot get feature list"); + return false; + } + + if (widgetType == WrtDB::APP_TYPE_TIZENWEBAPP) { + JavaScriptObject jsObject = { m_objectInstance, + m_shortUri }; + return PluginLogicSingleton::Instance().loadPluginOnDemand( + handle, jsObject, const_cast(m_context)); + } + + //check does plugin with feature was requested + FOREACH(it, features) + { + if (it->pluginId == handle) { + if (it->rejected) { + _E("Feature rejected by ACE"); + continue; + } + + JavaScriptObject jsObject = { m_objectInstance, + m_shortUri }; + + return PluginLogicSingleton::Instance().loadPluginOnDemand( + handle, jsObject, + const_cast(m_context)); + } + } + _E("Plugin not loaded"); + return false; +} + +JSValueRef PluginManager::getProperty(const string &name) const +{ + _D("getProperty %s", name.c_str()); + ObjectList::const_iterator it = m_objectList.find(name); + if (it != m_objectList.end()) { + //return already set value + return it->second; + } + + if (!loadChild(name)) { + ThrowMsg(Commons::PlatformException, "Cannot load plugin"); + } + + it = m_objectList.find(name); + if (it != m_objectList.end()) { + //return set value + return it->second; + } + + ThrowMsg(Commons::PlatformException, "Cannot obtain property"); +} + +bool PluginManager::setProperty(const string &name, + JSValueRef value) +{ + _D("setProperty %s", name.c_str()); + if (m_objectList.count(name) > 0) { + JSValueUnprotect(m_context, m_objectList[name]); + } + JSValueProtect(m_context, value); + m_objectList[name] = value; + return true; +} + +bool PluginManager::deleteProperty(const string &name) +{ + if (m_objectList.count(name) > 0) { + _D("deleteProperty %s", name.c_str()); + JSValueUnprotect(m_context, m_objectList[name]); + m_objectList.erase(name); + return true; + } + return false; +} + +Api::IPluginManager::PropertyList PluginManager::getProperties() const +{ + using namespace WrtDB; + + if (!!m_propertyCache) { + return *m_propertyCache; + } + + m_propertyCache = PropertyList(); + + WidgetDAOReadOnly dao(m_widgetHandle); + string localUri = m_objectUri + SEPARATOR; + + if (dao.getWidgetType() == APP_TYPE_TIZENWEBAPP) + { + static ImplementedObjectsList implObjectList = + PluginDAOReadOnly::getImplementedObjects(); + + FOREACH(it_implObject, implObjectList) + { + //check if implemented object stats with localUri + if (it_implObject->find(localUri) == 0) { + string property = *it_implObject; + //remove local uri that predicts property name. + property.erase(0, localUri.size()); + //check if property has its own properties. + size_t pos = property.find(SEPARATOR); + if (pos != string::npos) { + //if so then remove them. + property.erase(pos); + } + + m_propertyCache->push_back(property); + } + } + } + else + { + DbWidgetFeatureSet features; + + Try + { + features = dao.getFeaturesList(); + } + Catch(WidgetDAOReadOnly::Exception::Base) + { + _E("Cannot get feature list"); + ReThrow(Commons::PlatformException); + } + + DbWidgetFeatureSet::const_iterator feature = features.begin(); + for (; feature != features.end(); ++feature) { + ImplementedObjectsList implObjs = + PluginDAOReadOnly::getImplementedObjectsForPluginHandle( + feature->pluginId); + FOREACH(it, implObjs) { + //check if implemented object stats with localUri + if (it->find(localUri) == 0) { + string property = *it; + //remove local uri that predicts property name. + property.erase(0, localUri.size()); + //check if property has its own properties. + size_t pos = property.find(SEPARATOR); + if (pos != string::npos) { + //if so then remove them. + property.erase(pos); + } + m_propertyCache->push_back(property); + } + } + } + } + + return *m_propertyCache; +} + +void PluginManager::addPropertiesToList( + JSPropertyNameAccumulatorRef propertyNames) const +{ + PropertyList properties = getProperties(); + CommonsJavaScript::Converter converter(m_context); + FOREACH(it, properties) { + JSStringRef name = converter.toJSStringRef(*it); + JSPropertyNameAccumulatorAddName(propertyNames, name); + JSStringRelease(name); + } +} +} +} diff --git a/src_wearable/modules/tizen/PluginManager/PluginManager.h b/src_wearable/modules/tizen/PluginManager/PluginManager.h new file mode 100644 index 0000000..143b683 --- /dev/null +++ b/src_wearable/modules/tizen/PluginManager/PluginManager.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file PluginManager.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_PLUGINMANAGER_PLUGINMANAGER_H_ +#define WRTDEVICEAPIS_PLUGINMANAGER_PLUGINMANAGER_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +namespace PluginManager { +class PluginManager : public Api::IPluginManager +{ + public: + PluginManager(int widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context); + ~PluginManager(); + bool hasChild(const std::string &name) const; + bool loadChild(const std::string &name) const; + + JSValueRef getProperty(const std::string &name) const; + bool setProperty(const std::string &name, + JSValueRef value); + bool deleteProperty(const std::string &name); + + PropertyList getProperties() const; + void addPropertiesToList(JSPropertyNameAccumulatorRef propertyNames) const; + + private: + typedef std::map ObjectList; + + int m_widgetHandle; + JSObjectRef m_objectInstance; + std::string m_objectUri; + std::string m_shortUri; + mutable boost::optional m_propertyCache; + ObjectList m_objectList; + JSContextRef m_context; +}; +} +} + +#endif diff --git a/src_wearable/modules/tizen/PluginManager/config.cmake b/src_wearable/modules/tizen/PluginManager/config.cmake new file mode 100644 index 0000000..ccf3c80 --- /dev/null +++ b/src_wearable/modules/tizen/PluginManager/config.cmake @@ -0,0 +1,23 @@ +get_current_path() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +#pkg_search_module(wrt-plugin-loading REQUIRED wrt-plugin-loading) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${wrt-plugin-loading_INCLUDE_DIRS} + ${PLUGIN_LOADING_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${dpl-wrt-dao-ro_LIBRARIES} + ${wrt-plugin-loading_LIBRARIES} + ${TARGET_PLUGIN_LOADING_LIB} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${CURRENT_PATH}/PluginManager.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/tizen/Widget/Property.h b/src_wearable/modules/tizen/Widget/Property.h new file mode 100644 index 0000000..d1a19d1 --- /dev/null +++ b/src_wearable/modules/tizen/Widget/Property.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file Property.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WIDGET_PROPERTY_H_ +#define WIDGET_PROPERTY_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace Widget { +template +class Property +{ + public: + explicit Property() : + m_value(), + m_valid(false) + {} + + void setValue(const T& value) + { + m_value = value; + m_valid = true; + } + + T getValue() const + { + if (!m_valid) { + Throw(Commons::PlatformException); + } + return m_value; + } + + bool isValid() const + { + return m_valid; + } + + virtual ~Property() + {} + + private: + T m_value; + bool m_valid; +}; + +typedef Property StringProperty; +typedef Property UIntProperty; +} +} +#endif diff --git a/src_wearable/modules/tizen/Widget/Widget.cpp b/src_wearable/modules/tizen/Widget/Widget.cpp new file mode 100644 index 0000000..d250452 --- /dev/null +++ b/src_wearable/modules/tizen/Widget/Widget.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file Widget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include +#include +#include "Widget.h" +#include +#include + +namespace WrtDeviceApis { +namespace Widget { +using namespace std; +using namespace WidgetDB::Api; + +Widget::Widget() +{ + using namespace WrtDeviceApis::Commons; + m_widgetId = WrtAccessSingleton::Instance().getWidgetId(); +} + +Widget::~Widget() +{} + +string Widget::getProperty(ConfigAttribute attr) const +{ + checkWidgetId(); + + string value; + Try { + IWidgetDBPtr widgetDB = getWidgetDB(m_widgetId); + value = widgetDB->getConfigValue(attr); + } + Catch(Commons::InvalidArgumentException){ + LogError("Invalid argument exception"); + Throw(Commons::PlatformException); + } + + return value; +} + +string Widget::getAuthor() const +{ + checkWidgetId(); + + if (!m_author.isValid()) { + m_author.setValue(getProperty(ConfigAttribute::AUTHOR_NAME)); + } + return m_author.getValue(); +} + +string Widget::getAuthorEmail() const +{ + checkWidgetId(); + + if (!m_authorEmail.isValid()) { + m_authorEmail.setValue(getProperty(ConfigAttribute::AUTHOR_EMAIL)); + } + return m_authorEmail.getValue(); +} + +string Widget::getAuthorHref() const +{ + checkWidgetId(); + + if (!m_authorHref.isValid()) { + m_authorHref.setValue(getProperty(ConfigAttribute::AUTHOR_HREF)); + } + return m_authorHref.getValue(); +} + +string Widget::getDescription() const +{ + checkWidgetId(); + + if (!m_description.isValid()) { + m_description.setValue(getProperty(ConfigAttribute::DESCRIPTION)); + } + return m_description.getValue(); +} + +string Widget::getId() const +{ + checkWidgetId(); + + LogDebug("entered"); + if (!m_id.isValid()) { + m_id.setValue(getProperty(ConfigAttribute::ID)); + } + return m_id.getValue(); +} + +string Widget::getName() const +{ + checkWidgetId(); + + if (!m_name.isValid()) { + m_name.setValue(getProperty(ConfigAttribute::NAME)); + } + return m_name.getValue(); +} + +string Widget::getShortName() const +{ + checkWidgetId(); + + if (!m_shortName.isValid()) { + m_shortName.setValue(getProperty(ConfigAttribute::SHORT_NAME)); + } + return m_shortName.getValue(); +} + +string Widget::getVersion() const +{ + checkWidgetId(); + + if (!m_version.isValid()) { + m_version.setValue(getProperty(ConfigAttribute::VERSION)); + } + return m_version.getValue(); +} + +unsigned int Widget::getHeight() const +{ + checkWidgetId(); + + if (!m_height.isValid()) { + m_height.setValue(Commons::String::convertTo( + getProperty(ConfigAttribute::HEIGHT))); + } + return m_height.getValue(); +} + +unsigned int Widget::getWidth() const +{ + checkWidgetId(); + + if (!m_width.isValid()) { + m_width.setValue(Commons::String::convertTo( + getProperty(ConfigAttribute::WIDTH))); + } + return m_width.getValue(); +} + +void Widget::checkWidgetId() const +{ + if (m_widgetId < 0) { + LogError("Invalid widget id"); + Throw(Commons::InvalidArgumentException); + } + return; +} +} +} diff --git a/src_wearable/modules/tizen/Widget/Widget.h b/src_wearable/modules/tizen/Widget/Widget.h new file mode 100644 index 0000000..1dee043 --- /dev/null +++ b/src_wearable/modules/tizen/Widget/Widget.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * + * @file Widget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef PLATFORM_WIDGET_CONFIGURATION_H_ +#define PLATFORM_WIDGET_CONFIGURATION_H_ + +#include + +#include + +#include +#include +#include "Property.h" + +namespace WrtDeviceApis { +namespace Widget { +class Widget : public Api::IWidget +{ + public: + + explicit Widget(); + ~Widget(); + + virtual std::string getAuthor() const; + virtual std::string getAuthorEmail() const; + virtual std::string getAuthorHref() const; + virtual std::string getDescription() const; + virtual std::string getId() const; + virtual std::string getName() const; + virtual std::string getShortName() const; + virtual std::string getVersion() const; + virtual unsigned int getHeight() const; + virtual unsigned int getWidth() const; + + protected: + + mutable StringProperty m_author; + mutable StringProperty m_authorEmail; + mutable StringProperty m_authorHref; + mutable StringProperty m_description; + mutable StringProperty m_id; + mutable StringProperty m_name; + mutable StringProperty m_shortName; + mutable StringProperty m_version; + mutable UIntProperty m_height; + mutable UIntProperty m_width; + + private: + + std::string getProperty(WidgetDB::Api::ConfigAttribute) const; + void checkWidgetId() const; + + int m_widgetId; +}; +} +} + +#endif diff --git a/src_wearable/modules/tizen/Widget/config.cmake b/src_wearable/modules/tizen/Widget/config.cmake new file mode 100644 index 0000000..c4a3adf --- /dev/null +++ b/src_wearable/modules/tizen/Widget/config.cmake @@ -0,0 +1,6 @@ +get_current_path() + +set(SRCS_IMPLEMENTATION_WIDGET + ${CURRENT_PATH}/Widget.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/tizen/WidgetDB/WidgetDB.cpp b/src_wearable/modules/tizen/WidgetDB/WidgetDB.cpp new file mode 100644 index 0000000..f2813b4 --- /dev/null +++ b/src_wearable/modules/tizen/WidgetDB/WidgetDB.cpp @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file WidgetDB.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#include "WidgetDB.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "WidgetFeature.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +WidgetDB::WidgetDB(int widgetId) : m_widgetId(widgetId) {} + +int WidgetDB::getWidgetId() const +{ + return m_widgetId; +} + +std::string WidgetDB::getLanguage() const +{ + LogDebug("getting language"); + + WrtDB::LanguageTagList languageTags; + std::string outLanguage; + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + languageTags = dao.getLanguageTags(); + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + // get 'en' language or first from the list if 'en' does not exist + if (languageTags.size() > 1) { + FOREACH(lang, languageTags) + { + if ("en" == DPL::ToUTF8String(*lang)) { + return "en"; + } + } + } + + if (!languageTags.empty()) { + // get first language tag + outLanguage = DPL::ToUTF8String(*(languageTags.begin())); + } + return outLanguage; +} + +/*License,LicenseHref,Description,Name can be \ + * returned with incorect language*/ +std::string WidgetDB::getConfigValue(Api::ConfigAttribute attribute) const +{ + LogDebug("entered"); + std::string value; + Try + { + WrtDB::WidgetDAOReadOnlyPtr dao(new WrtDB::WidgetDAOReadOnly(getWidgetId())); + WrtDB::WidgetLocalizedInfo widgetInfo = + W3CFileLocalization::getLocalizedInfo(dao); + + std::ostringstream out; + + switch (attribute) { + case Api::ConfigAttribute::ID: { + DPL::OptionalString val = dao->getGUID(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::VERSION: { + DPL::OptionalString val = dao->getVersion(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::DESCRIPTION: { + DPL::OptionalString val = widgetInfo.description; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::LICENSE: { + DPL::OptionalString val = widgetInfo.license; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::LICENSE_HREF: { + DPL::OptionalString val = widgetInfo.licenseHref; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_NAME: { + DPL::OptionalString val = dao->getAuthorName(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_EMAIL: { + DPL::OptionalString val = dao->getAuthorEmail(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_HREF: { + DPL::OptionalString val = dao->getAuthorHref(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::NAME: { + DPL::OptionalString val = widgetInfo.name; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::SHORT_NAME: { + DPL::OptionalString val = widgetInfo.shortName; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::WIDTH: { + DPL::OptionalInt width = dao->getPreferredSize().width; + !width ? out << "0" : out << *width; + value = out.str(); + break; + } + + case Api::ConfigAttribute::HEIGHT: { + DPL::OptionalInt height = dao->getPreferredSize().height; + !height ? out << "0" : out << *height; + value = out.str(); + break; + } + + case Api::ConfigAttribute::INSTALL_PATH: + value = DPL::ToUTF8String(dao->getPath()); + break; + + case Api::ConfigAttribute::PUBLIC_STORAGE_PATH: + value = WrtDB::GlobalConfig::GetPublicVirtualRootPath(); + break; + + default: + LogWarning("Unknown attribute requested"); + Throw(Commons::InvalidArgumentException); + } + } + Catch(Commons::InvalidArgumentException) + { + ReThrow(Commons::InvalidArgumentException); + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + LogDebug("exit"); + + return value; +} + +std::string WidgetDB::getUserAgent() const +{ + LogDebug("Widget User_Agent data get"); + + std::string outUA("not implemented"); + return outUA; +} + +Api::InstallationStatus WidgetDB::checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const +{ + LogDebug("Checking widget ( gid(" << gid << "), name(" << name << + "), version(" << version << ")) installation status"); + + Api::InstallationStatus outStatus; + Try + { + const WrtDB::WidgetGUID w_guid = + WrtDB::WidgetGUID(DPL::FromUTF8String(gid)); + + try { + WrtDB::DbWidgetHandle widgetHandle = + WrtDB::WidgetDAOReadOnly::getHandle(w_guid); + + WrtDB::WidgetDAOReadOnly dao(widgetHandle); + DPL::OptionalString ver = dao.getVersion(); + if (!ver || version > DPL::ToUTF8String(*ver)) { + // if there is no version in DB + // or DB version is lover or equal than provided + outStatus = Api::InstallationStatus::STATUS_INSTALLED; + } else { + outStatus = Api::InstallationStatus::STATUS_LATEST; + } + } catch (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist) { + outStatus = Api::InstallationStatus::STATUS_UNINSTALLED; + } + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + return outStatus; +} + +Api::Features WidgetDB::getWidgetFeatures() const +{ + LogDebug("entered"); + WrtDB::DbWidgetFeatureSet features; + Try + { + WrtDB::WidgetDAOReadOnly doa(getWidgetId()); + features = doa.getFeaturesList(); + } + Catch(DPL::Exception) + { + // exception handle + ReThrow(Commons::SecurityException); + } + + Api::Features outFeatures; + + LogDebug("There is no exception"); + + FOREACH(it, features) + { + Api::IWidgetFeaturePtr feature( + new WidgetFeature(DPL::ToUTF8String((*it).name), + true)); // requested (WidgetFeature param) + outFeatures.push_back(feature); + } + + return outFeatures; +} + +Api::Features WidgetDB::getRegisteredFeatures() const +{ + Api::Features outRegisteredFeatures; + Try + { + // initialize with our widget features (they are required) + outRegisteredFeatures = getWidgetFeatures(); + + // searching for another features + + WrtDB::FeatureHandleList features = + WrtDB::FeatureDAOReadOnly::GetHandleList(); + + bool featureFound = false; + + // throught all features + FOREACH(registeredFeature, features) + { + WrtDB::FeatureHandle handle = *registeredFeature; + WrtDB::FeatureDAOReadOnly dao(handle); + + // check if this feature is aleready on outRegisteredFeatures list + // and if not, add it + + FOREACH(it, outRegisteredFeatures) + { + if (dao.GetName() == (*it)->getName()) { // *it = shared ptr + // this name is found on list, do not add + featureFound = true; + break; + } + } + + if (!featureFound) { + // feature is not on outRegisteredFeature so add it with + // 'required' property false + Api::IWidgetFeaturePtr newFeature(new WidgetFeature( + dao.GetName(), + false)); + + // TODO what about feature params? aren't they needed + outRegisteredFeatures.push_back(newFeature); + } + // reset the flag and check another feature + featureFound = false; + } + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + return outRegisteredFeatures; +} + +std::string WidgetDB::getWidgetInstallationPath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + std::string result(DPL::ToUTF8String(dao.getFullPath())); + result.erase(0, strlen("file://")); + std::string::size_type pos = result.size(); + std::string separator("/"); + pos = result.rfind(separator, pos); + if ((result.size() - pos) > 0 && (result.size() - pos) < 2) { + result.erase(pos, result.size()); + } + return result; + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetDB::getWidgetPersistentStoragePath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + return + WrtDB::WidgetConfig::GetWidgetPersistentStoragePath( + dao.getTizenPkgId()); + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetDB::getWidgetTemporaryStoragePath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + return + WrtDB::WidgetConfig::GetWidgetTemporaryStoragePath( + dao.getTizenPkgId()); + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} +} // WidgetDB +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/WidgetDB/WidgetDB.h b/src_wearable/modules/tizen/WidgetDB/WidgetDB.h new file mode 100644 index 0000000..b471e1a --- /dev/null +++ b/src_wearable/modules/tizen/WidgetDB/WidgetDB.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file WidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H_ +#define WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +class WidgetDB : public Api::IWidgetDB +{ + public: + + explicit WidgetDB(int widgetId); + + virtual int getWidgetId() const; + + virtual std::string getLanguage() const; + + virtual std::string getConfigValue(Api::ConfigAttribute attribute) const; + + virtual std::string getUserAgent() const; + + virtual Api::InstallationStatus checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const; + + virtual Api::Features getWidgetFeatures() const; + + virtual Api::Features getRegisteredFeatures() const; + + virtual std::string getWidgetInstallationPath() const; + + virtual std::string getWidgetPersistentStoragePath() const; + + virtual std::string getWidgetTemporaryStoragePath() const; + + private: + + int m_widgetId; +}; +} // WidgetDB +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H + diff --git a/src_wearable/modules/tizen/WidgetDB/WidgetFeature.cpp b/src_wearable/modules/tizen/WidgetDB/WidgetFeature.cpp new file mode 100644 index 0000000..aee4902 --- /dev/null +++ b/src_wearable/modules/tizen/WidgetDB/WidgetFeature.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include "WidgetFeature.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +WidgetFeature::WidgetFeature(const std::string& name, + bool requested) : + m_name(name), + m_requested(requested) +{ + //LogDebug("entered"); +} + +std::string WidgetFeature::getName() const +{ + //LogDebug("entered"); + return m_name; +} + +WidgetFeature::~WidgetFeature() +{ + //LogDebug("entered"); +} + +bool WidgetFeature::isRequestedByWidget() const +{ + return m_requested; +} +} // WidgetDB +} // WrtDeviceApis diff --git a/src_wearable/modules/tizen/WidgetDB/WidgetFeature.h b/src_wearable/modules/tizen/WidgetDB/WidgetFeature.h new file mode 100644 index 0000000..d14dc69 --- /dev/null +++ b/src_wearable/modules/tizen/WidgetDB/WidgetFeature.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_H_ +#define WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_H_ + +#include +#include + +namespace WrtDeviceApis { +namespace WidgetDB { +class WidgetFeature : public Api::IWidgetFeature +{ + public: + WidgetFeature(const std::string& name, + bool requested); + + std::string getName() const; + + virtual ~WidgetFeature(); + + virtual bool isRequestedByWidget() const; + + private: + std::string m_name; + bool m_requested; +}; +} // WidgetDB +} // WrtDeviceApis + +#endif diff --git a/src_wearable/modules/tizen/WidgetDB/config.cmake b/src_wearable/modules/tizen/WidgetDB/config.cmake new file mode 100644 index 0000000..6362668 --- /dev/null +++ b/src_wearable/modules/tizen/WidgetDB/config.cmake @@ -0,0 +1,22 @@ +get_current_path() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(dpl-utils-efl REQUIRED dpl-utils-efl) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_WIDGETDB + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${dpl-utils-efl_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_WIDGETDB + ${dpl-wrt-dao-ro_LDFLAGS} + ${dpl-utils-efl_LDFLAGS} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_WIDGETDB + ${CURRENT_PATH}/WidgetDB.cpp + ${CURRENT_PATH}/WidgetFeature.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/tizen/WidgetInterface/CMakeLists.txt b/src_wearable/modules/tizen/WidgetInterface/CMakeLists.txt new file mode 100644 index 0000000..883f3d1 --- /dev/null +++ b/src_wearable/modules/tizen/WidgetInterface/CMakeLists.txt @@ -0,0 +1,6 @@ + +get_current_path() + +pkg_search_module(wrt-commons-widget-interface-dao REQUIRED wrt-commons-widget-interface-dao) + +include_directories(${CURRENT_PATH}) diff --git a/src_wearable/modules/tizen/WidgetInterface/WidgetInterface.cpp b/src_wearable/modules/tizen/WidgetInterface/WidgetInterface.cpp new file mode 100644 index 0000000..d535151 --- /dev/null +++ b/src_wearable/modules/tizen/WidgetInterface/WidgetInterface.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include "WidgetInterface.h" +#include +#include +#include +#include +#include +#include + +namespace WrtDeviceApis { +using namespace WidgetInterfaceDB; + +WidgetInterfaceObject::WidgetInterfaceObject(int widgetHandle) +{ + Try + { + m_dao.reset(new WidgetInterfaceDAO(widgetHandle)); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +WidgetInterfaceObject::~WidgetInterfaceObject() +{ + m_dao.reset(); +} + +void WidgetInterfaceObject::setItem(const std::string& key, + const std::string& value, + bool readOnly) +{ + Try + { + m_dao->setItem(key, value, readOnly); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::LocalStorageValueNoModifableException) + { + LogError("Cannot delete item. Item is readonly"); + ReThrow(Commons::LocalStorageValueNoModifableException); + } +} + +void WidgetInterfaceObject::removeItem(const std::string& key) +{ + Try + { + m_dao->removeItem(key); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::LocalStorageValueNoModifableException) + { + LogError("Cannot delete item. Item is readonly"); + ReThrow(Commons::LocalStorageValueNoModifableException); + } +} + +DPL::OptionalStdString WidgetInterfaceObject::getValue( + const std::string& key) const +{ + Try + { + return m_dao->getValue(key); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +void WidgetInterfaceObject::clear(bool removeReadOnly) +{ + Try + { + m_dao->clear(removeReadOnly); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +size_t WidgetInterfaceObject::getStorageSize() const +{ + Try + { + return m_dao->getStorageSize(); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetInterfaceObject::getKeyByIndex(size_t index) const +{ + Try + { + return m_dao->getKeyByIndex(index); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::InvalidArgumentException) + { + ReThrow(Commons::InvalidArgumentException); + } +} +} diff --git a/src_wearable/modules/tizen/WidgetInterface/WidgetInterface.h b/src_wearable/modules/tizen/WidgetInterface/WidgetInterface.h new file mode 100644 index 0000000..80065ad --- /dev/null +++ b/src_wearable/modules/tizen/WidgetInterface/WidgetInterface.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ +#define WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ + +#include +#include +#include +#include + +namespace WrtDeviceApis { +class WidgetInterfaceObject : + public LocalStorage::Api::ILocalStorage +{ + public: + WidgetInterfaceObject(int widgetHandle); + virtual ~WidgetInterfaceObject(); + + void setItem(const std::string& key, + const std::string& value, + bool readOnly); + void removeItem(const std::string& key); + DPL::OptionalStdString getValue(const std::string& key) const; + void clear(bool removeReadOnly); + size_t getStorageSize() const; + std::string getKeyByIndex(size_t index) const; + + private: + WidgetInterfaceDB::WidgetInterfaceDAOPtr m_dao; +}; +} + +#endif //WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ diff --git a/src_wearable/modules/tizen/WidgetInterface/config.cmake b/src_wearable/modules/tizen/WidgetInterface/config.cmake new file mode 100644 index 0000000..a69d23e --- /dev/null +++ b/src_wearable/modules/tizen/WidgetInterface/config.cmake @@ -0,0 +1,17 @@ + +get_current_path() + +set(WIDGET_INTERFACE_INCLUDE_DIRS + ${CURRENT_PATH} + PARENT_SCOPE +) + +SET(API_WIDGET_INTERFACE_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_WIDGET_INTERFACE + ${CURRENT_PATH}/WidgetInterface.cpp + PARENT_SCOPE +) diff --git a/src_wearable/modules/tizen/config.cmake b/src_wearable/modules/tizen/config.cmake new file mode 100644 index 0000000..82b25da --- /dev/null +++ b/src_wearable/modules/tizen/config.cmake @@ -0,0 +1,3 @@ +include_config_file(Widget) +include_config_file(StorageEvent) +include_config_file(LocalStorage) \ No newline at end of file diff --git a/src_wearable/plugin-loading/CMakeLists.txt b/src_wearable/plugin-loading/CMakeLists.txt new file mode 100644 index 0000000..fbcf48a --- /dev/null +++ b/src_wearable/plugin-loading/CMakeLists.txt @@ -0,0 +1,80 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# + +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) +pkg_search_module(dpl REQUIRED dpl-efl) +pkg_search_module(dpl-event REQUIRED dpl-event-efl) +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(webkit2 REQUIRED ewebkit2) + +set(PLUGIN_LOADING_SOURCES + ${PLUGIN_LOADING_DIRS}/plugin_logic.cpp + ${PLUGIN_LOADING_DIRS}/plugin.cpp + ${PLUGIN_LOADING_DIRS}/plugin_model.cpp + ${PLUGIN_LOADING_DIRS}/explorer.cpp + ${PLUGIN_LOADING_DIRS}/plugin_iframe_support.cpp + ${PLUGIN_LOADING_DIRS}/plugin_container_support.cpp + ${PLUGIN_LOADING_DIRS}/plugin_property_support.cpp + ${PLUGIN_LOADING_DIRS}/javascript_interface.cpp + ${PLUGIN_LOADING_DIRS}/js_page_session.cpp +) + +INCLUDE_DIRECTORIES( + ${PLUGIN_MODULE_SRC_DIR} + ${PLUGIN_LOADING_DIRS} + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGIN_LOADING_LIB} SHARED + ${PLUGIN_LOADING_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_PLUGIN_LOADING_LIB} + ${dpl_LIBRARIES} + ${dpl-event_LIBRARIES} + ${dpl-wrt-dao-ro_LIBRARIES} + ${TARGET_COMMONS} + ${TARGET_JS_OVERLAY} + wrt-plugins-tizen-service-event # static lib + wrt-plugins-softkeyboardchange-event # static lib +) + +INSTALL(TARGETS ${TARGET_PLUGIN_LOADING_LIB} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +# For wrt-plugins +INSTALL(FILES + ${PLUGIN_LOADING_DIRS}/plugin_logic.h + ${PLUGIN_LOADING_DIRS}/js_types.h + DESTINATION include/wrt-plugin-loading) diff --git a/src_wearable/plugin-loading/explorer.cpp b/src_wearable/plugin-loading/explorer.cpp new file mode 100644 index 0000000..1d5d8c3 --- /dev/null +++ b/src_wearable/plugin-loading/explorer.cpp @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file explorer.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @author Yunchan Cho (yunchan.cho@samgsung.com) + * @version + * @brief + */ + +#include +#include +#include +#include "explorer.h" +#include "plugin_property_support.h" + +// JS overlay +#include + +namespace { +//const char* SEPARATOR = "."; +const std::string GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; +} + +using namespace std; +using namespace PluginModule; +using namespace WrtPlugins::W3C; + +Explorer::Explorer(JSGlobalContextRef context) : + m_context(context) +{ + if (!context) { + _W("Context is NULL"); + return; + } + + m_globalObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + + //register main frame; + m_iframeSupport.registerIframe(m_globalObject); + + m_propertySupport.reset(new WindowPropertySupport(m_context)); +} + +Explorer::~Explorer() +{ +} + +JSObjectPtr Explorer::getJSObjectProperty(const std::string& propertyName, + JSObjectPtr object) +{ + return JavaScriptInterfaceSingleton::Instance().getJSObjectProperty( + m_context, object, propertyName); +} + +JSObjectPtr Explorer::getProperty( + const string& requestedProperty, + JSObjectPtr providedObject) +{ + _D("Requested Property: %s", requestedProperty.c_str()); + + if (!providedObject) { + _W("Provided object is empty"); + return JSObjectPtr(); + } + + std::string currentObjectName; + std::string currentPropertyRequested = requestedProperty; + JSObjectPtr currentObject = providedObject; + + while (true) { + auto pos = currentPropertyRequested.find("."); + if (pos == string::npos) { + return getJSObjectProperty(currentPropertyRequested, currentObject); + } + + //check if requested object has child + currentObjectName = currentPropertyRequested.substr(0, pos); + + if (currentPropertyRequested.size() <= pos + 1) { + _W("Wrong name of requested property"); + return JSObjectPtr(); + } + currentPropertyRequested = currentPropertyRequested.substr(pos + 1); + + currentObject = getJSObjectProperty(currentObjectName, currentObject); + if (!currentObject) { + _W("Failed to get property: %s", currentObjectName.c_str()); + return JSObjectPtr(); + } + } +} + +bool Explorer::registerObject(const JSObjectDeclarationPtr& declaration, + JSGlobalContextRef context) +{ + bool retValue; + + if (declaration->getParentName() == GLOBAL_OBJECT_NAME) { + retValue = register_(declaration, m_globalObject, context); + } else { //PIM support + //it should be master object name + string masterName = declaration->getParentName(); + auto pos = masterName.find("."); + if (string::npos != pos) { + _W("ParentName not allowed"); + return false; + } + auto masterObject = getJSObjectProperty(masterName, m_globalObject); + if (masterObject->getObject() == 0) { + return false; + } + retValue = registerObject(declaration, + masterName, + masterObject, + context); + } + + if (declaration->checkIframesSupported()) { + m_iframeSupport.registerDeclaration(declaration); + // m_iframeSupport.invokeCallbackForMainFrame(m_context, + // declaration, + // newObject); + } + + return retValue; +} + +bool Explorer::registerObject(const JSObjectDeclarationPtr& declaration, + const std::string& providedObjectName, + JSObjectPtr providedObject, + JSGlobalContextRef context) +{ + _D("%s <- %s", providedObjectName.c_str(), declaration->getName().c_str()); + std::string fullParentName = declaration->getParentName(); + + if (fullParentName == providedObjectName) { + _D("Provided object was matched!!"); + return register_(declaration, providedObject, context); + } + + //check if object exists in fullParentName + auto pos = fullParentName.find(providedObjectName); + if (pos == string::npos) { + _W("Object: %s should be child of: %s but you provided object: %s", + declaration->getName().c_str(), + declaration->getParentName().c_str(), + providedObjectName.c_str()); + return false; + } + + if (fullParentName.size() <= pos + providedObjectName.size() + 1) { + _W("Invalid object name"); + return false; + } + + auto currentRequesteProperty = + fullParentName.substr(pos + providedObjectName.size() + 1); + + JSObjectPtr jsObject = getProperty( + currentRequesteProperty, providedObject); + + if (!jsObject->getObject()) { + _W("Object: %s should be child of: %s. you provided object: %s but object is null", + declaration->getName().c_str(), + declaration->getParentName().c_str(), + providedObjectName.c_str()); + return false; + } + + return register_(declaration, jsObject, context); +} + +bool Explorer::register_(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parent, + JSGlobalContextRef context) +{ + _D("Registration object: %s <- %s", + declaration->getParentName().c_str(), + declaration->getName().c_str()); + AssertMsg(parent, "parent object is NULL"); + + typedef JSObjectDeclaration::Options JO; + + JSGlobalContextRef gContext = (context == NULL) ? m_context : context; + JSObjectPtr objectInstance = JavaScriptInterfaceSingleton::Instance(). + createObject(gContext, declaration); + + JavaScriptInterfaceSingleton::Instance().setObjectProperty( + gContext, + parent, + declaration->getName(), + objectInstance); + + //notice + if (declaration->getOptions() && + (declaration->getOptions()->getIframeNotice() == + JO::IFrameNotice::AlwaysNotice)) + { + declaration->getOptions()->invokeCallback(gContext, + parent->getObject(), + objectInstance->getObject()); + } + + return true; +} + +void Explorer::registerObjectIntoIframe( + const JSObjectDeclarationPtr& declaration, + JSObjectPtr frameObject, + JSGlobalContextRef context) +{ + if (declaration->getParentName() == GLOBAL_OBJECT_NAME) { + _D("Connect to Global object of IFRAME"); + register_(declaration, frameObject, context); + return; + } + + //PIM SUPPORT + { + _D("Connect to NOT global object of IFRAME"); + //it should be master object name + string masterName = declaration->getParentName(); + auto pos = masterName.find("."); + if (string::npos != pos) { + _W("ParentName not allowed"); + return; + } + auto masterObject = getJSObjectProperty(masterName, frameObject); + if (!masterObject->getObject()) { + _W("Object not exist in frame"); + return; + } + register_(declaration, masterObject, context); + } +} + +void Explorer::loadFrame(JSGlobalContextRef context) +{ + JSObjectPtr frameObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + + if (frameObject->getObject() == m_globalObject->getObject()) { + // Main page was already loaded from constructor + _W("Main page loaded"); + return; + } + + m_iframeSupport.registerIframe(frameObject); + + auto iframeObjects = m_iframeSupport.getIframeObjects(); + + FOREACH(object, iframeObjects) + { + _D("Register object: %s", (*object)->getName().c_str()); + registerObjectIntoIframe(*object, frameObject, context); + } +} + +void Explorer::unloadFrame(JSGlobalContextRef context) +{ + JSObjectPtr frameObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + m_iframeSupport.unregisterIframe(frameObject); +} + +void Explorer::removePluginsFromIframes() +{ + if (m_iframeSupport.hasIframes()) { + JavaScriptInterfaceSingleton::Instance().removeIframes(m_context); + } +} + +void Explorer::deregisterObject(const JSObjectDeclarationPtr& declaration) +{ + if (GLOBAL_OBJECT_NAME != declaration->getParentName()) { + _W("Ignored remove property %s", declaration->getName().c_str()); + return; + } + + JavaScriptInterfaceSingleton::Instance(). + removeObjectProperty(m_context, + m_globalObject, + declaration->getName()); +} + +void Explorer::cleanIframesData() +{ + m_iframeSupport.clean(); +} + +void Explorer::callEventListeners(CustomEventType /*eventType*/, void* /*data*/) +{ +#if 0 // deprecated + using namespace WrtPlugins::Tizen; + // get iframe objects from javascript global context + JavaScriptInterface::ObjectsListPtr frameLists = + JavaScriptInterfaceSingleton::Instance().getIframesList(m_context); + + // get main frame object from javascript global context + JSObjectRef mainFrame = JSContextGetGlobalObject(m_context); + frameLists->push_back(JSObjectPtr(new JSObject(mainFrame))); + + if (eventType == ServiceCustomEvent) { + using namespace WrtDeviceApis::TizenServiceEvent::Api; + // set user data of js callback function for 'appservice' js event + ITizenServiceEventPtr event = ITizenServiceEventPtr( + new TizenServiceEvent()); + event->setScale(m_propertySupport->getScale()); + event->setBundle(m_propertySupport->getBundle()); + + // call js callback function for 'appservice' js event on each frame + FOREACH(it, *frameLists) + { + JSObjectRef frame = static_cast((*it).Get()->getObject()); + + auto eventPriv = + new JSTizenServiceEventPrivateObject(m_context, event); + JSObjectRef eventObject = + JSObjectMake(m_context, + JSTizenServiceEvent::getClassRef(), eventPriv); + + AddEventListenerSupport::CallCustomEventListenersFromIFrame( + frame, eventType, eventObject); + } + } else if (eventType == SoftKeyboardChangeCustomEvent) { + using namespace WrtDeviceApis::SoftKeyboardChangeEvent::Api; + if (!data) { + LogDebug("no ime size"); + return; + } + + // set user data of js callback function for 'softkeyboardchange' js + // event + SoftKeyboardChangeArgs* args = + static_cast(data); + ISoftKeyboardChangeEventPtr event = + ISoftKeyboardChangeEventPtr( + new SoftKeyboardChangeEvent( + args->state, + args->width, + args->height)); + LogDebug("softkeyboard event's state: " << args->state); + + // call js callback function for 'softkeyboardchange' js event on each + // frame + FOREACH(it, *frameLists) + { + JSObjectRef frame = static_cast((*it).Get()->getObject()); + + auto eventPriv = + new JSSoftKeyboardChangeEventPrivateObject(m_context, event); + JSObjectRef eventObject = + JSObjectMake( + m_context, + JSSoftKeyboardChangeEvent::getClassRef(), + eventPriv); + + AddEventListenerSupport::CallCustomEventListenersFromIFrame( + frame, eventType, eventObject); + } + } else { + LogDebug("Not supported custom event type"); + return; + } +#endif +} + +WindowPropertySupport* Explorer::getWindowPropertySupport() +{ + return m_propertySupport.get(); +} diff --git a/src_wearable/plugin-loading/explorer.h b/src_wearable/plugin-loading/explorer.h new file mode 100644 index 0000000..60d2fb6 --- /dev/null +++ b/src_wearable/plugin-loading/explorer.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file explorer.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_EXPLORER_H_ +#define WRT_SRC_PLUGIN_SERVICE_EXPLORER_H_ + +#include + +#include +#include +#include + +#include +#include +//JSGlobalContextRef +#include "javascript_interface.h" +#include "plugin_iframe_support.h" +#include "plugin_property_support.h" + +//JS overlay +#include + +using namespace PluginModule; +using namespace WrtPlugins::W3C; + +class Explorer : private DPL::Noncopyable +{ + public: + explicit Explorer(JSGlobalContextRef context); + ~Explorer(); + + //register to global frame + bool registerObject(const JSObjectDeclarationPtr& declaration, + JSGlobalContextRef context); + + bool registerObject (const JSObjectDeclarationPtr& declaration, + const std::string& parentObjectName, + JSObjectPtr parentObject, + JSGlobalContextRef context); + + void deregisterObject(const JSObjectDeclarationPtr& declaration); + + // new load/unload frame API + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void removePluginsFromIframes(); + void cleanIframesData(); + void callEventListeners(CustomEventType eventType, void* data); + + WindowPropertySupport* getWindowPropertySupport(); + + private: + + IframesSupport m_iframeSupport; + + //globalContext + JSGlobalContextRef m_context; + + //global object of main frame + JSObjectPtr m_globalObject; + + std::unique_ptr m_propertySupport; + + private: + void registerObjectIntoIframe(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parentObject, + JSGlobalContextRef context); + + bool register_(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parent, + JSGlobalContextRef context); + + JSObjectPtr getJSObjectProperty(const std::string& propertyName, + JSObjectPtr object); + + JSObjectPtr getProperty( + const std::string& requestedProperty, + JSObjectPtr providedObject); +}; + +typedef DPL::SharedPtr ExplorerPtr; +#endif diff --git a/src_wearable/plugin-loading/javascript_interface.cpp b/src_wearable/plugin-loading/javascript_interface.cpp new file mode 100644 index 0000000..5dc8f9f --- /dev/null +++ b/src_wearable/plugin-loading/javascript_interface.cpp @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_webkit.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of webkit js plugin + * accessing routines in EFL + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +IMPLEMENT_SINGLETON(JavaScriptInterface) + +#define CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, object, ret) \ + if (JSValueIsUndefined(context, object)) { \ + _E("Object %s is undefined", #object); \ + return ret; \ + } + +#define CHECK_JSOBJECT_IS_NULL_RETURN(object, ret) \ + if (!object) { \ + _E("Object %s is NULL", #object); \ + return ret; \ + } + +namespace { +/** + * Converts JSStringRef to std::string + * */ +std::string toString(const JSStringRef& arg) +{ + Assert(arg); + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(arg); + if (jsSize > 0) { + ++jsSize; + DPL::ScopedArray buffer(new char[jsSize]); + size_t written = JSStringGetUTF8CString(arg, buffer.Get(), jsSize); + if (written > jsSize) { + _E("Conversion could not be fully performed."); + return std::string(); + } + result = buffer.Get(); + } + + return result; +} + +/** + * Converts JSValueRef to std::string + * */ +std::string toString(JSContextRef ctx, JSValueRef value) +{ + Assert(ctx && value); + std::string result; + JSStringRef str = JSValueToStringCopy(ctx, value, NULL); + result = toString(str); + JSStringRelease(str); + return result; +} + +JSValueRef getProperty(JSContextRef ctx, JSValueRef value, const char* name) +{ + Assert(ctx && value && name); + JSValueRef result = NULL; + JSObjectRef obj = JSValueToObject(ctx, value, NULL); + if (obj) { + JSStringRef str = JSStringCreateWithUTF8CString(name); + result = JSObjectGetProperty(ctx, obj, str, NULL); + JSStringRelease(str); + } + return result; +} + +JSValueRef getPropertyObj(JSContextRef ctx, JSObjectRef obj, const char* name) +{ + Assert(ctx && obj && name); + JSStringRef str = JSStringCreateWithUTF8CString(name); + JSValueRef result = JSObjectGetProperty(ctx, obj, str, NULL); + JSStringRelease(str); + return result; +} + +JSObjectRef getJSGlobalObject(JSGlobalContextRef context) +{ + return JSContextGetGlobalObject(context); +} +} + +typedef JSValueRef (*JSCFunction)( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + +void JavaScriptInterface::setObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName, + const JSObjectPtr& propertyObject) +{ + _D("JSObjectSetProperty(%p, \"%s\")", context, propertyName.c_str()); + + //create name + JSStringRef name = JSStringCreateWithUTF8CString(propertyName.c_str()); + //set property + JSObjectSetProperty( + static_cast(context), + static_cast(parentObject->getObject()), name, + static_cast(propertyObject->getObject()), + kJSPropertyAttributeReadOnly, 0); + + JSStringRelease(name); +} + +void JavaScriptInterface::removeObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName) +{ + if (!context) { + //nothing to do -> no context + return; + } + _D("JSObjectDeleteProperty(%p, \"%s\")", context, propertyName.c_str()); + + JSStringRef name = JSStringCreateWithUTF8CString(propertyName.c_str()); + JSObjectDeleteProperty( + static_cast(context), + static_cast(parentObject->getObject()), name, 0); + + JSStringRelease(name); +} + +JavaScriptInterface::PropertiesList JavaScriptInterface:: + getObjectPropertiesList( + JSGlobalContextRef context, + const JSObjectPtr& object) const +{ + PropertiesList result; + JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames( + static_cast(context), + static_cast(object->getObject())); + std::size_t count = JSPropertyNameArrayGetCount(properties); + result.reserve(count); + _D("propesties count %d", count); + for (std::size_t i = 0; i < count; ++i) { + JSStringRef property = JSPropertyNameArrayGetNameAtIndex(properties, i); + result.push_back(toString(property)); + } + JSPropertyNameArrayRelease(properties); + return result; +} + +JSObjectPtr JavaScriptInterface::makeJSFunctionObject( + JSGlobalContextRef context, + const std::string &name, + js_function_impl functionImplementation) const +{ + _D("JSObjectMakeFunctionWithCallback(%p, \"%s\")", context, name.c_str()); + JSStringRef jsFunName = JSStringCreateWithUTF8CString(name.c_str()); + + JSObjectRef object = JSObjectMakeFunctionWithCallback( + context, + jsFunName, + reinterpret_cast( + functionImplementation)); + + JSStringRelease(jsFunName); + return JSObjectPtr(new JSObject(static_cast(object))); +} + +JSObjectPtr JavaScriptInterface::makeJSClassObject( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate) const +{ + _D("JSObjectMake(%p)", context); + JSObjectRef object = JSObjectMake( + context, + static_cast( + const_cast(classTemplate)), + NULL); + return JSObjectPtr(new JSObject(object)); +} + +JSObjectPtr JavaScriptInterface::makeJSObjectBasedOnInterface( + JSGlobalContextRef context, + const std::string &interfaceName) const +{ + _D("makeJSObjectBasedOnInterface(%p, \"%s\")", context, interfaceName.c_str()); + JSObjectPtr jsInterfaceObj = getJSObjectProperty(context, + getGlobalObject( + context), + interfaceName); + JSObjectRef object = JSObjectCallAsConstructor(context, + static_cast( + jsInterfaceObj-> + getObject()), 0, + NULL, + NULL); + return JSObjectPtr(new JSObject(static_cast(object))); +} + +JSObjectPtr JavaScriptInterface::makeJSInterface( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate, + JSObjectDeclaration::ConstructorCallback constructorCallback) const +{ + _D("makeJSInterface(%p)", context); + JSObjectRef object = JSObjectMakeConstructor(context, + static_cast( + const_cast< + JSObjectDeclaration:: + ClassTemplate>( + classTemplate)), + reinterpret_cast< + JSObjectCallAsConstructorCallback>( + constructorCallback) + ); + return JSObjectPtr(new JSObject(static_cast(object))); +} + +JSObjectPtr JavaScriptInterface::createObject( + JSGlobalContextRef context, + const JSObjectDeclarationPtr& + declaration) +{ + typedef JSObjectDeclaration::Options JO; + + if (declaration->getOptions()) { + switch (declaration->getOptions()->getType()) { + case JO::ClassType::Function: + return makeJSFunctionObject( + context, + declaration->getName(), + declaration->getOptions()->getFunctionImpl()); + + case JO::ClassType::Class: + if (declaration->getInterfaceName().empty()) { + return makeJSClassObject( + context, + declaration->getClassTemplate()); + } else { + return makeJSObjectBasedOnInterface( + context, + declaration->getInterfaceName()); + } + + case JO::ClassType::Interface: + return makeJSInterface( + context, + /* product class template */ + declaration->getClassTemplate(), + declaration->getConstructorCallback()); + + default: + _E("Invalid class type. Making empty JS object."); + return JSObjectPtr(new JSObject( + JSObjectMake(context, NULL, NULL))); + } + } else { + _D("No declaration options"); + return JSObjectPtr(new JSObject( + JSObjectMake( + context, + static_cast( + const_cast( + declaration->getClassTemplate())), + NULL))); + } +} + +JSObjectPtr JavaScriptInterface::getGlobalObject(JSGlobalContextRef context) +const +{ + return JSObjectPtr(new JSObject(static_cast( + JSContextGetGlobalObject(static_cast< + JSGlobalContextRef>( + context))))); +} + +JSObjectPtr JavaScriptInterface::copyObjectToIframe( + JSGlobalContextRef context, + const JSObjectPtr& iframe, + const std::string& name) +{ + _D("copyObjectToIframe(%s)", name.c_str()); + + JSGlobalContextRef jsGlobalContext = + static_cast(context); + + JSObjectRef globalObject = JSContextGetGlobalObject(jsGlobalContext); + + JSValueRef requestedObject = getPropertyObj(jsGlobalContext, + globalObject, + name.c_str()); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(jsGlobalContext, + requestedObject, + JSObjectPtr()); + + JSStringRef requestedObjectStr = + JSStringCreateWithUTF8CString(name.c_str()); + + JSObjectSetProperty(jsGlobalContext, + static_cast(iframe->getObject()), + requestedObjectStr, + requestedObject, + kJSPropertyAttributeReadOnly, + NULL); + + JSStringRelease(requestedObjectStr); + + return JSObjectPtr( + new JSObject(const_cast(requestedObject))); +} + +JavaScriptInterface::ObjectsListPtr +JavaScriptInterface::getIframesList(JSGlobalContextRef ctx) const +{ + JSGlobalContextRef context = static_cast(ctx); + JSObjectRef globalObject = JSContextGetGlobalObject(context); + ObjectsListPtr retList = getIframesList(context, globalObject); + + return retList; +} + +JavaScriptInterface::ObjectsListPtr +JavaScriptInterface::getIframesList(JSContextRef context, + JSObjectRef globalObject) const +{ + JSValueRef frames = getPropertyObj(context, globalObject, "frames"); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, frames, ObjectsListPtr()); + + JSObjectRef frames_o = JSValueToObject(context, frames, NULL); + CHECK_JSOBJECT_IS_NULL_RETURN(frames_o, ObjectsListPtr()); + + JSValueRef len = getPropertyObj(context, frames_o, "length"); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, len, ObjectsListPtr()); + + size_t count = JSValueToNumber(context, len, NULL); + _D("frames_o.length = %%d", count); + + ObjectsListPtr retList = ObjectsListPtr(new ObjectsList()); + + for (size_t i = 0; i < count; ++i) { + std::stringstream ss; + ss << i; + JSValueRef frame = getPropertyObj(context, + frames_o, + ss.str().c_str()); + if (JSValueIsUndefined(context, frame)) { + _E("Selected frame is null: frame[%d]", i); + continue; + } + JSObjectRef frame_obj = JSValueToObject(context, frame, NULL); + if (!frame_obj) { + _E("frame_obj is NULL."); + continue; + } + retList->push_back(JSObjectPtr(new JSObject(frame_obj))); + ObjectsListPtr childList = getIframesList(context, frame_obj); + + retList->merge(*childList); + _D("Frame Value Pointer: %p", frame); + _D("Frame Object Pointer: %p", frame_obj); + } + + return retList; +} + +JSObjectPtr JavaScriptInterface::getJSObjectProperty(JSGlobalContextRef ctx, + const JSObjectPtr& frame, + const std::string& name) +const +{ + _D("makeJSObjectBasedOnInterface(%p, \"%s\")", ctx, name.c_str()); + JSObjectRef frame_js = static_cast(frame->getObject()); + JSValueRef property = getPropertyObj(ctx, frame_js, name.c_str()); + JSObjectRef objProp = JSValueToObject(ctx, property, NULL); + + return JSObjectPtr(new JSObject(objProp)); +} + +void JavaScriptInterface::removeIframes(JSGlobalContextRef context) +{ + const char* deleteIframesScript = + "frame_set = document.getElementsByTagName('iframe');" + "len = frame_set.length;" + "for(i=0; i< len; i++)" + " frame_set[0].parentNode.removeChild(frame_set[0]); "; + + JSGlobalContextRef ctx = static_cast(context); + + JSStringRef script_src = JSStringCreateWithUTF8CString(deleteIframesScript); + + JSEvaluateScript(ctx, script_src, 0, 0, 0, 0); + + JSStringRelease(script_src); +} + +void JavaScriptInterface::invokeGarbageCollector(JSGlobalContextRef context) +{ + LogDebug("Garbage collection"); + JSGarbageCollect(context); + JSGarbageCollect(context); + JSGarbageCollect(context); + JSGarbageCollect(context); +} diff --git a/src_wearable/plugin-loading/javascript_interface.h b/src_wearable/plugin-loading/javascript_interface.h new file mode 100644 index 0000000..c3aa171 --- /dev/null +++ b/src_wearable/plugin-loading/javascript_interface.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file JavaScriptInterface.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRT_SRC_PLUGIN_SERVICE_WEBKIT_INTERFACE_H_ +#define WRT_SRC_PLUGIN_SERVICE_WEBKIT_INTERFACE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +//forward declaration of JSConectexRef +extern "C" { +typedef const struct OpaqueJSContext* JSContextRef; +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +class JavaScriptInterface : DPL::Noncopyable +{ + public: + + typedef std::vector PropertiesList; + + typedef std::list ObjectsList; + typedef std::shared_ptr ObjectsListPtr; + + public: + JSObjectPtr getGlobalObject(JSGlobalContextRef context) const; + + // object creation + JSObjectPtr createObject(JSGlobalContextRef context, + const JSObjectDeclarationPtr& declaration); + + //properties + void setObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName, + const JSObjectPtr& propertyObject); + + void removeObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName); + + PropertiesList getObjectPropertiesList(JSGlobalContextRef context, + const JSObjectPtr& object) const; + + JSObjectPtr copyObjectToIframe(JSGlobalContextRef context, + const JSObjectPtr& iframe, + const std::string& name); + + ObjectsListPtr getIframesList(JSGlobalContextRef context) const; + + void removeIframes(JSGlobalContextRef context); + + void invokeGarbageCollector(JSGlobalContextRef context); + + JSObjectPtr getJSObjectProperty(JSGlobalContextRef ctx, + const JSObjectPtr& frame, + const std::string& name) const; + + private: + JavaScriptInterface() + {} + + JSObjectPtr makeJSFunctionObject( + JSGlobalContextRef context, + const std::string &name, + js_function_impl functionImplementation) const; + JSObjectPtr makeJSClassObject( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate) const; + JSObjectPtr makeJSObjectBasedOnInterface( + JSGlobalContextRef context, + const std::string &interfaceName) const; + JSObjectPtr makeJSInterface( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate, + JSObjectDeclaration::ConstructorCallback constructorCallback) const; + + ObjectsListPtr getIframesList(JSContextRef context, + JSObjectRef object) const; + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton JavaScriptInterfaceSingleton; + +#endif diff --git a/src_wearable/plugin-loading/js_page_session.cpp b/src_wearable/plugin-loading/js_page_session.cpp new file mode 100644 index 0000000..96de957 --- /dev/null +++ b/src_wearable/plugin-loading/js_page_session.cpp @@ -0,0 +1,600 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_logic.cpp + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and + * feature loading routines + * @brief This code is intended to work behind view controller + */ + +#include "plugin_logic.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "explorer.h" +#include "plugin.h" +#include "plugin_model.h" +#include "javascript_interface.h" +#include "js_function_manager.h" +#include "plugin_container_support.h" + +#include "js_page_session.h" + +using namespace std; +using namespace WrtDB; +using namespace WrtPlugins::W3C; + +namespace { +const char *LIBRARY_PATH_SEPARATOR = "/"; +} + +class JSPageSession::Impl +{ + private: + typedef std::set LoadedPlugins; + typedef std::set LoadedContexts; + + private: + ///< Widget handle using this session + int m_widgetHandle; + + //view for this session + JSGlobalContextRef m_context; + + bool m_sessionStarted; + + ///< JS object explorer for this session + Explorer* m_objectExplorer; + + PluginContainerSupportPtr m_pluginsSupport; + + ///< All loaded plugins. Each one must be unloaded. Plugins means + //set of features connected with such plugin (library) + LoadedPlugins m_loadedPlugins; + + // Set of currently loaded web pages' contexts. These contexts are + // exactly matching with each frames' global context. + LoadedContexts m_loadedContexts; + + private: + PluginPtr loadLibrary(PluginModelPtr& pluginModel); + + void installStandardFunctions(); + void installRootPlugins(); + void installRequestedFeatures(); + + //returns true if success or false if failed + bool installPlugin(PluginModelPtr plugin); + bool installPluginOnDemand(PluginModelPtr plugin, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void unloadPluginsFromSession(); + + public: + Impl(const PluginContainerSupportPtr& containerSupport); + ~Impl(); + + // Widget session + void startSession(int widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(); + + void performLibrariesUnload(); + + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(CustomEventType eventType, void* data); +}; + +JSPageSession::Impl::Impl(const PluginContainerSupportPtr& support) : + m_widgetHandle(0), + m_context(NULL), + m_sessionStarted(false), + m_objectExplorer(NULL) +{ + _D("Initializing Page Session"); + m_pluginsSupport = support; +} + +JSPageSession::Impl::~Impl() +{ + if (m_sessionStarted) { + LogError("Must stop widget session before exit!"); + stopSession(); + } + + _D("Deinitializing Page Session"); +} + + void JSPageSession::Impl::installStandardFunctions() + { + _D("========== install standard Functions START =========="); + + //add standard functions + FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) { + m_objectExplorer->registerObject(*it, NULL); + } + + _D("========== install standard Functions END =========="); + } + +void JSPageSession::Impl::installRootPlugins() +{ + _D("========== install root Functions START =========="); + + PluginContainerSupport::PluginsList rootPlugins = + m_pluginsSupport->getRootPlugins(); + FOREACH(it, rootPlugins) + { + installPlugin(*it); + } + + _D("========== install root Functions END =========="); +} + +bool JSPageSession::Impl::installPlugin(PluginModelPtr plugin) +{ + AssertMsg(plugin, "Plugin Model is NULL"); + PluginPtr library = loadLibrary(plugin); + + if (!library) { + _E("Loading library failed"); + return false; + } + + _D("Install Plugin : %s", library->GetFileName().c_str()); + + // Register new class + FOREACH(it, *(library->GetClassList())) + { + if (!m_objectExplorer->registerObject(*it, NULL)) { + _E("Object Registration failed : %s", (*it)->getName().c_str()); + } + } + return true; +} + +void JSPageSession::Impl::installRequestedFeatures() +{ + _D("========== install requested Features START =========="); + + std::list allowedFeatures = + m_pluginsSupport->getAllowedFeatures(m_widgetHandle); + + PluginContainerSupport::PluginsList allowedPlugins; + + FOREACH(feature, allowedFeatures) + { + _D("Processing feature: %s", (*feature).c_str()); + + PluginModelPtr plugin = m_pluginsSupport->getPluginForFeature(*feature); + + if (!plugin) { + _W("It didn't have plugins! : %s", (*feature).c_str()); + continue; + } + + ImplementedObjectsList implObjs = + PluginDAOReadOnly:: + getImplementedObjectsForPluginHandle(plugin->Handle.Get()); + + FOREACH(obj, implObjs) + { + _D("Processing object: %s", (*obj).c_str()); + /* This can be optimalized, but would need extra data in database. + * There should be a list of features that are allowed to be + * installed at widget start */ + if (obj->find(".") == obj->rfind(".")) { + allowedPlugins.push_back(plugin); + _D("Plugin will be added: %s", plugin->LibraryName.Get().c_str()); + break; + } + } + } + + FOREACH(plugin, allowedPlugins) + { + _D("Installation plugin: %s", (*plugin)->LibraryName.Get().c_str()); + installPlugin(*plugin); + } + + _D("========== install requested Features END =========="); +} + +bool JSPageSession::Impl::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + AssertMsg(parentObject.instance && !parentObject.name.empty(), + "Wrong arguments"); + + if (!m_sessionStarted) { + _W("Session not started"); + return false; + } + // //TODO here may be a bug. if plugin contains feature rejected and + // accepted + // LogDebug("Installing feature : " << widgetFeature.name); + // if (widgetFeature.rejected) { + // LogWarning("This api-feature was rejected"); + // return; + // } + // + // auto plugin = m_pluginsSupport->getPluginModelById(pluginHandle); + // if (!plugin) { + // LogError("Failed to load plugin. plugin handle: " << + // pluginHandle); + // return false; + // } + m_pluginsSupport->registerPluginModel(pluginHandle); + return installPluginOnDemand( + m_pluginsSupport->getPluginModelById(pluginHandle), + parentObject, + context); +} + +bool JSPageSession::Impl::installPluginOnDemand(PluginModelPtr plugin, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + AssertMsg(plugin, "Plugin Model is NULL"); + PluginPtr library = loadLibrary(plugin); + + if (!library) { + _E("Loading library failed"); + return false; + } + + _D("Install Plugin %s", library->GetFileName().c_str()); + + if (!(parentObject.instance)) { + _E("NULL pointer value"); + return false; + } + + JSObjectPtr parent(new JSObject(parentObject.instance)); + + if (!parent->getObject()) { + _E("NULL pointer value"); + assert(false); + return false; + } + + FOREACH(it, *(library->GetClassList())) + { + bool installationStatus = + m_objectExplorer->registerObject(*it, + parentObject.name, + parent, + context); + + if (!installationStatus) { + _E("Object Registration failed : %s; Parent object name: %s", + (*it)->getName().c_str(), + parentObject.name.c_str()); + return false; + } + } + + _D("Plugin on demand registration completed"); + return true; +} + +void JSPageSession::Impl::setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_objectExplorer->getWindowPropertySupport() + ->setScaleToNavigatorProperty(scaleFactor); + m_objectExplorer->getWindowPropertySupport() + ->setBundleToWindowProperty(encodedBundle); + m_objectExplorer->getWindowPropertySupport() + ->setThemeToNavigatorProperty(theme); +} + +void JSPageSession::Impl::dispatchJavaScriptEvent(CustomEventType eventType, + void* data) +{ + // Check if session is already started + if (!m_sessionStarted) { + _W("Session not started!"); + return; + } + m_objectExplorer->callEventListeners(eventType, data); +} + +void JSPageSession::Impl::startSession(int widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + + // Check if corresponding session if not already created + if (m_sessionStarted) { + _W("Session already started!"); + return; + } + + // Create js object explorer object + m_objectExplorer = new Explorer(context); + + m_sessionStarted = true; + m_widgetHandle = widgetHandle; + m_loadedPlugins.clear(); + m_context = context; + + // Register standard features + installStandardFunctions(); + + WidgetDAOReadOnly dao(m_widgetHandle); + WidgetType appType = dao.getWidgetType(); + if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) { + installRootPlugins(); + } + // Register special features + installRequestedFeatures(); + + // set scale, bundle as window's property + setCustomProperties(scaleFactor, encodedBundle, theme); +} + +void JSPageSession::Impl::stopSession() +{ + if (!m_sessionStarted) { + _W("Session not started!"); + return; + } + + unloadPluginsFromSession(); + m_sessionStarted = false; +} + +void JSPageSession::Impl::unloadPluginsFromSession() +{ + m_objectExplorer->removePluginsFromIframes(); + m_objectExplorer->cleanIframesData(); + + // delete js object for overlayed js functions + FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) + { + m_objectExplorer->deregisterObject(*it); + } + + // delete js object for plugins + FOREACH(pluginIt, m_loadedPlugins) + { + _D("Unregistering plugin %s", (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnWidgetStop(m_widgetHandle); + + FOREACH(it, *((*pluginIt)->GetClassList())) { + m_objectExplorer->deregisterObject(*it); + } + } + + JavaScriptInterfaceSingleton::Instance().invokeGarbageCollector(m_context); + + m_loadedPlugins.clear(); + + delete m_objectExplorer; + m_objectExplorer = NULL; +} + +void JSPageSession::Impl::performLibrariesUnload() +{ +#if 0 + LogDebug("Perform library unload"); + + size_t unloadedLibraries = 0; + + FOREACH(pluginIt, m_loadedPlugins) + { + LogDebug("Preparing library: " << (*pluginIt)->LibraryName.Get()); + + PluginPtr plugin = (*pluginIt)->LibraryInstance.Get(); + if (!plugin) { + LogWarning("Library not loaded " << (*pluginIt)->LibraryName.Get()); + continue; + } + unloadedLibraries++; + (*pluginIt)->LibraryInstance.Set(PluginPtr()); + } + + LogDebug("unloaded " << unloadedLibraries << " unreferenced libraries!"); +#endif +} + +PluginPtr JSPageSession::Impl::loadLibrary(PluginModelPtr& pluginModel) +{ + PluginPtr pluginLib = pluginModel->LibraryInstance.Get(); + if (!pluginLib) { + std::string path = pluginModel->LibraryPath.Get() + + std::string(LIBRARY_PATH_SEPARATOR) + + pluginModel->LibraryName.Get(); + + pluginLib = Plugin::LoadFromFile(path); + + if (!pluginLib) { + _E("Loading library failed"); + } else { + pluginModel->LibraryInstance.Set(pluginLib); + + _D("On widget start"); + // This is first time for this plugin, start widget Session + pluginLib->OnWidgetStart( + m_widgetHandle); + m_loadedPlugins.insert(pluginLib); + + FOREACH(context, m_loadedContexts) + { + pluginLib->OnFrameLoad(*context); + } + } + } else { + _D("Get from LibraryInstance"); + _D("On widget start"); + // This is first time for this plugin, start widget Session + pluginLib->OnWidgetStart( + m_widgetHandle); + m_loadedPlugins.insert(pluginLib); + + FOREACH(context, m_loadedContexts) + { + pluginLib->OnFrameLoad(*context); + } + } + + return pluginLib; +} + +void JSPageSession::Impl::loadFrame(JSGlobalContextRef context) +{ + if (!m_sessionStarted) { + _W("Session NOT started!"); + return; + } + + m_loadedContexts.insert(context); + + FOREACH(pluginIt, m_loadedPlugins) + { + _D("Try to call 'OnFrameLoad' callback : %s", + (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnFrameLoad(context); + } + + m_objectExplorer->loadFrame(context); +} + +void JSPageSession::Impl::unloadFrame(JSGlobalContextRef context) +{ + if (!m_sessionStarted) { + _W("Session NOT started!"); + return; + } + + m_loadedContexts.erase(context); + + FOREACH(pluginIt, m_loadedPlugins) + { + _D("Try to call 'OnFrameUnload' callback : %s", + (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnFrameUnload(context); + } + + m_objectExplorer->unloadFrame(context); +} + +void JSPageSession::startSession(int widgetHandle, + JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme); +} + +void JSPageSession::stopSession() +{ + m_impl->stopSession(); +} + +void JSPageSession::performLibrariesUnload() +{ + m_impl->performLibrariesUnload(); +} + +bool JSPageSession::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context); +} + +void JSPageSession::setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->setCustomProperties(scaleFactor, encodedBundle, theme); +} + +void JSPageSession::dispatchJavaScriptEvent(CustomEventType eventType, + void* data) +{ + m_impl->dispatchJavaScriptEvent(eventType, data); +} + +void JSPageSession::loadFrame(JSGlobalContextRef context) +{ + m_impl->loadFrame(context); +} + +void JSPageSession::unloadFrame(JSGlobalContextRef context) +{ + m_impl->unloadFrame(context); +} + +JSPageSession::JSPageSession(const PluginContainerSupportPtr& containerSupport) + : + m_impl(new JSPageSession::Impl(containerSupport)) +{} + +JSPageSession::~JSPageSession() +{} diff --git a/src_wearable/plugin-loading/js_page_session.h b/src_wearable/plugin-loading/js_page_session.h new file mode 100644 index 0000000..3580287 --- /dev/null +++ b/src_wearable/plugin-loading/js_page_session.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_page_session.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ +#ifndef WRT_PLUGIN_JS_PAGE_SESSION_H_ +#define WRT_PLUGIN_JS_PAGE_SESSION_H_ + +#include +#include +#include +#include +#include "js_types.h" + +using namespace WrtPlugins::W3C; + +class JSPageSession +{ + public: + // Widget session + void startSession(int widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(); + + //TODO im not sure if it is needed. I think it should be hidden + void performLibrariesUnload(); + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + // reset custom window properties. (Tizen requirements) + void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(CustomEventType eventType, void* data); + + JSPageSession(const PluginContainerSupportPtr& containerSupport); + + virtual ~JSPageSession(); + + private: + class Impl; + std::unique_ptr m_impl; +}; + +typedef std::shared_ptr JSPageSessionPtr; + +#endif // PLUGIN_LOGIC_H diff --git a/src_wearable/plugin-loading/js_types.h b/src_wearable/plugin-loading/js_types.h new file mode 100644 index 0000000..076582e --- /dev/null +++ b/src_wearable/plugin-loading/js_types.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_types.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#ifndef WRT_PLUGIN_JS_TYPES_H_ +#define WRT_PLUGIN_JS_TYPES_H_ + +//forward declaration of JSConectexRef +extern "C" { +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +struct JavaScriptObject +{ + JSObjectRef instance; + std::string name; +}; + +#endif diff --git a/src_wearable/plugin-loading/plugin.cpp b/src_wearable/plugin-loading/plugin.cpp new file mode 100644 index 0000000..f486500 --- /dev/null +++ b/src_wearable/plugin-loading/plugin.cpp @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin + */ +#include "plugin.h" +#include +#include +#include + +Plugin::Plugin(const std::string &fileName, + void *libHandle, + on_widget_start_proc *apiOnWidgetStart, + on_widget_init_proc *apiOnWidgetInit, + on_widget_stop_proc *apiOnWidgetStop, + on_frame_load_proc* apiOnFrameLoad, + on_frame_unload_proc* apiOnFrameUnload, + const ClassPtrList &apiClassList) : + m_fileName(fileName), + m_libHandle(libHandle), + m_apiOnWidgetStart(apiOnWidgetStart), + m_apiOnWidgetInit(apiOnWidgetInit), + m_apiOnWidgetStop(apiOnWidgetStop), + m_apiOnFrameLoad(apiOnFrameLoad), + m_apiOnFrameUnload(apiOnFrameUnload), + m_apiClassList(apiClassList) +{} + +Plugin::~Plugin() +{ + _D("Unloading plugin library: %s", m_fileName.c_str()); + + // Unload library + if (dlclose(m_libHandle) != 0) { + _E("Cannot close plugin handle"); + } else { + _D("Library is unloaded"); + } +} + +PluginPtr Plugin::LoadFromFile(const std::string& fileName) +{ + static bool logEnable = (getenv("WRT_LOAD_PLUGINS_LOG_ENABLE") != NULL); + + _D("LoadFromFile %s", fileName.c_str()); + + void *dllHandle; + dllHandle = dlopen(fileName.c_str(), RTLD_LAZY); + + _D("dlopen() done!"); + + if (dllHandle == NULL) { + const char* error = (const char*)dlerror(); + _E("Failed to load plugin: %s. Reason: %s", + fileName.c_str(), + (error != NULL ? error : "unknown")); + PluginPtr empty; + return empty; + } + + // Load new plugin API + on_widget_start_proc *onWidgetStartProcPtr = NULL; + on_widget_stop_proc *onWidgetStopProcPtr = NULL; + on_widget_init_proc *onWidgetInitProcPtr = NULL; + on_frame_load_proc *onFrameLoadProcPtr = NULL; + on_frame_unload_proc *onFrameUnloadProcPtr = NULL; + + const js_entity_definition_t *rawClassList = NULL; + get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL; + + onWidgetStartProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_WIDGET_START_PROC_NAME)); + onWidgetInitProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_WIDGET_INIT_PROC_NAME)); + onWidgetStopProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_WIDGET_STOP_PROC_NAME)); + onFrameLoadProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_FRAME_LOAD_PROC_NAME)); + onFrameUnloadProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_FRAME_UNLOAD_PROC_NAME)); + getWidgetEntityMapProcPtr = + reinterpret_cast( + dlsym(dllHandle, PLUGIN_GET_CLASS_MAP_PROC_NAME)); + + if (getWidgetEntityMapProcPtr) { + rawClassList = (*getWidgetEntityMapProcPtr)(); + + if (logEnable) { + _D("rawClassList : %p by getWidgetClassMapProcPtr()", + rawClassList); + } + } else { + rawClassList = + static_cast(dlsym(dllHandle, + PLUGIN_CLASS_MAP_NAME)); + if (logEnable) { _D("rawClassList : %p", rawClassList); } + } + + if (NULL == onWidgetStartProcPtr || NULL == onWidgetStopProcPtr || + /*NULL == onWidgetInitProcPtr ||*/ NULL == rawClassList) + { + if (logEnable) { + _W("#####"); + _W("##### Warning: The following plugin does not support new plugin API."); + _W("##### Old plugin API is deprecated. Please update it to new API"); + _W("#####"); + _W("##### Plugin: %s has got deprecated or invalid API", fileName.c_str()); + _W("#####"); + } + + // Will not load plugin + dlclose(dllHandle); + + PluginPtr empty; + return empty; + } + + if (logEnable) { + _D("#####"); + _D("##### Plugin: %s supports new plugin API", fileName.c_str()); + _D("#####"); + _D("##### $onWidgetStartProc: %p", onWidgetStartProcPtr); + _D("##### $onWidgetInitProc: %p", onWidgetInitProcPtr); + _D("##### $onWidgetStopProc %p", onWidgetStopProcPtr); + _D("##### $onFrameLoadProc %p", onFrameLoadProcPtr); + _D("##### $onFrameUnloadProc %p", onFrameUnloadProcPtr); + _D("##### $classMap: %p", reinterpret_cast(rawClassList)); + _D("##### "); + _D("##### Class map:"); + } + + const js_entity_definition_t *rawEntityListIterator = rawClassList; + ClassPtrList classList(new Plugin::ClassList()); + + // Parse all class definitions + while (rawEntityListIterator->parent_name != NULL && + rawEntityListIterator->object_name != NULL) + { + if (logEnable) + { + // Logging + _D("#####"); + _D("##### [%s]", rawEntityListIterator->object_name); + _D("##### Interface: %s", rawEntityListIterator->interface_name); + _D("##### Parent: %s", rawEntityListIterator->parent_name); + } + + // Register class + classList->push_back(ClassPtr(new Class(rawEntityListIterator))); + + // Go to next class + ++rawEntityListIterator; + } + + // Load export table + _D("Plugin successfuly loaded"); + + // Insert to loaded modules list + + PluginPtr instance(new Plugin(fileName, + dllHandle, + onWidgetStartProcPtr, + onWidgetInitProcPtr, + onWidgetStopProcPtr, + onFrameLoadProcPtr, + onFrameUnloadProcPtr, + classList)); + + return instance; +} + +std::string Plugin::GetFileName() const +{ + return m_fileName; +} + +void Plugin::OnWidgetStart(int widgetId) +{ + if (NULL != m_apiOnWidgetStart) { + (*m_apiOnWidgetStart)(widgetId); + _D("Called!"); + } +} + +void Plugin::OnWidgetInit(feature_mapping_interface_t* mapping) +{ + AssertMsg(NULL != mapping, "NULL mapping interface provided"); + if (NULL != m_apiOnWidgetInit) { + (*m_apiOnWidgetInit)(mapping); + _D("Called!"); + } +} + +void Plugin::OnWidgetStop(int widgetId) +{ + if (NULL != m_apiOnWidgetStop) { + (*m_apiOnWidgetStop)(widgetId); + _D("Called!"); + } +} + +void Plugin::OnFrameLoad(java_script_context_t context) +{ + if (NULL != m_apiOnFrameLoad) { + (*m_apiOnFrameLoad)(context); + _D("Called!"); + } +} + +void Plugin::OnFrameUnload(java_script_context_t context) +{ + if (NULL != m_apiOnFrameUnload) { + (*m_apiOnFrameUnload)(context); + _D("Called!"); + } +} + +const Plugin::ClassPtrList Plugin::GetClassList() const +{ + return m_apiClassList; +} diff --git a/src_wearable/plugin-loading/plugin.h b/src_wearable/plugin-loading/plugin.h new file mode 100644 index 0000000..1eb277f --- /dev/null +++ b/src_wearable/plugin-loading/plugin.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin + */ +#ifndef WRT_SRC_PLUGIN_SERVICE_PLUGIN_H_ +#define WRT_SRC_PLUGIN_SERVICE_PLUGIN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +class Plugin; +typedef DPL::SharedPtr PluginPtr; + +class Plugin : private DPL::Noncopyable +{ + public: + typedef JSObjectDeclaration Class; + typedef JSObjectDeclarationPtr ClassPtr; + typedef std::list ClassList; + typedef DPL::SharedPtr ClassPtrList; + + private: + ///< Plug-in identifier. Currently plug-in file name is used as the ID + std::string m_fileName; + + ///< Handle for the plug-in library. A plug-in is a dynamic loadable library + void* m_libHandle; + + // Plugin API + on_widget_start_proc* m_apiOnWidgetStart; + on_widget_init_proc* m_apiOnWidgetInit; + on_widget_stop_proc* m_apiOnWidgetStop; + on_frame_load_proc* m_apiOnFrameLoad; + on_frame_unload_proc* m_apiOnFrameUnload; + const ClassPtrList m_apiClassList; + + Plugin(const std::string &fileName, + void *libHandle, + on_widget_start_proc* apiOnWidgetStart, + on_widget_init_proc* apiOnWidgetInit, + on_widget_stop_proc* apiOnWidgetStop, + on_frame_load_proc* apiOnFrameLoad, + on_frame_unload_proc* apiOnFrameUnload, + const ClassPtrList &apiClassList); + + public: + virtual ~Plugin(); + + // Loading + static PluginPtr LoadFromFile(const std::string &fileName); + + // Filename + std::string GetFileName() const; + + // API + void OnWidgetStart(int widgetId); + + void OnWidgetInit(feature_mapping_interface_t *interface); + + void OnWidgetStop(int widgetId); + + void OnFrameLoad(java_script_context_t context); + + void OnFrameUnload(java_script_context_t context); + + const ClassPtrList GetClassList() const; +}; + +#endif // PLUGIN_H diff --git a/src_wearable/plugin-loading/plugin_container_support.cpp b/src_wearable/plugin-loading/plugin_container_support.cpp new file mode 100644 index 0000000..064e8a4 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_container_support.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_container_support.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#include "plugin_container_support.h" + +#include + +#include +#include +#include +#include + + using namespace WrtDB; + +#include + +PluginContainerSupport::PluginContainerSupport() : + m_initialized(false), + m_widgetHandle(0) +{ + // Reading root plugins list from so files + readRootPluginsList(); +} + +PluginContainerSupport::~PluginContainerSupport() +{ + // Remove all plugin models + m_pluginModels.clear(); + + // Remove all feature models + m_featureModels.clear(); + } + +void PluginContainerSupport::Initialize(int widgetHandle) +{ + if (isInitialized() == true && m_widgetHandle != widgetHandle) { + // re-initialize required + m_initialized = false; + + m_pluginModels.clear(); + m_featureModels.clear(); + } + + if (isInitialized() == false) { + m_initialized = true; + m_widgetHandle = widgetHandle; + + readAllowedPlugins(widgetHandle); + readRootPlugins(widgetHandle); + } +} + +std::list PluginContainerSupport::getAllowedFeatures( + int widgetHandle) const +{ + //TODO it has to return LIST NOT SET!!! + WidgetDAOReadOnly widgetDao(widgetHandle); + DbWidgetFeatureSet features = widgetDao.getFeaturesList(); + + std::list allowedFeatures; + FOREACH(it, features) { + _D("Loading api-feature: %s", DPL::ToUTF8String(it->name).c_str()); + if (it->rejected) { + _W("Api-feature was rejected by ace. (Api-feature name: %s)", + it->name.c_str()); + continue; + } + + allowedFeatures.push_back(DPL::ToUTF8String(it->name)); + } + return allowedFeatures; +} + +void PluginContainerSupport::readAllowedPlugins(int widgetHandle) +{ + std::list allowedFeatures; + auto requested = getAllowedFeatures(widgetHandle); + FOREACH(f, requested) + { + allowedFeatures.push_back(*f); + } + + FeatureData* dt = NULL; + std::map featureDataList = FeatureDAOReadOnly::GetFeatures( + allowedFeatures); + DeviceCapList deviceCapabilities = + FeatureDAOReadOnly::GetDevCapWithFeatureHandle(); + FOREACH(data, featureDataList) { + dt = &(data->second); + registerPluginModel(dt->pluginHandle); + registerFeatureModel(data->first, dt, deviceCapabilities); + } +} + +void PluginContainerSupport::readRootPlugins(int widgetHandle) +{ + WidgetDAOReadOnly dao(widgetHandle); + WidgetType appType = dao.getWidgetType(); + if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) { + FOREACH(it_rootPluginHandle, m_rootPluginsList) + { + _D("*it_rootPluginHandle: %d", *it_rootPluginHandle); + registerPluginModel(*it_rootPluginHandle); + } + } else { + _D("Not defined app type"); + } +} + +void PluginContainerSupport::registerFeatureModel( + FeatureHandle handle, + FeatureData* data, + DeviceCapList + deviceCapabilities) +{ + FeatureModelPtr model = getFeatureModel(handle); + if (model) { + _D("Model for feature: %d already created", handle); + return; + } + + _D("Creating Model for feature: %d", handle); + + model.reset(new FeatureModel(handle)); + + std::set devCapList; + auto ret = deviceCapabilities.equal_range(handle); + for (auto devCapIt = ret.first; devCapIt != ret.second; devCapIt++) { + devCapList.insert((*devCapIt).second); + } + model->SetData(data->featureName, devCapList, data->pluginHandle); + m_featureModels.insert(model); +} + +void PluginContainerSupport::registerPluginModel(DbPluginHandle handle) +{ + PluginModelPtr model = getPluginModelById(handle); + + if (model) { + _D("Model for plugin: %d already registered", handle); + return; + } + + if (PluginDAOReadOnly::INSTALLATION_COMPLETED != + PluginDAOReadOnly::getInstallationStateForHandle(handle)) + { + _W("Failed To CreateModel for handle %d", handle); + return; + } + + model.Reset(new PluginModel(handle)); + + _D("Model Created. Handle: %d, name: %s", + handle, + model->LibraryName.Get().c_str()); + + m_pluginModels.insert(model); +} + +void PluginContainerSupport::readRootPluginsList() +{ + _D("Reading root plugins list from so files..."); + m_rootPluginsList = PluginDAOReadOnly::getRootPluginHandleList(); +} + +FeatureModelPtr +PluginContainerSupport::getFeatureModel(const std::string &name) const +{ + FOREACH(iter, m_featureModels) + { + if ((*iter)->Name.Get() == name) { + return *iter; + } + } + + return FeatureModelPtr(); +} + +FeatureModelPtr +PluginContainerSupport::getFeatureModel(const FeatureHandle handle) const +{ + FOREACH(iter, m_featureModels) + { + if ((*iter)->FHandle.Get() == handle) { + return *iter; + } + } + + return FeatureModelPtr(); +} + +PluginModelPtr +PluginContainerSupport::getPluginModelById(DbPluginHandle handle) const +{ + FOREACH(pluginModel, m_pluginModels) + { + if ((*pluginModel)->Handle.Get() == handle) { + return *pluginModel; + } + } + + return PluginModelPtr(); +} + +PluginModelPtr +PluginContainerSupport::getPluginModel(const FeatureModelPtr &feature) const +{ + if (!feature) { + _D("Null Ptr for feature model"); + return PluginModelPtr(); + } else { + _D("Feature located in plugin: %d", feature->PHandle.Get()); + return getPluginModelById(feature->PHandle.Get()); + } +} + + PluginContainerSupport::PluginsList +PluginContainerSupport::getRootPlugins() const +{ + PluginsList plugins; + + FOREACH(it, m_rootPluginsList) { + PluginModelPtr plugin = getPluginModelById(*it); + if (!plugin) { + _W("PluginModel not found"); + continue; + } + + plugins.push_back(plugin); + } + + return plugins; +} + +PluginContainerSupport::PluginsList +PluginContainerSupport::getPluginsList() const +{ + PluginsList plugins; + + FOREACH(it, m_pluginModels) { + plugins.push_back(*it); + } + + return plugins; +} + +PluginModelPtr +PluginContainerSupport::getPluginForFeature(const std::string& featureName) +{ + return getPluginModel(getFeatureModel(featureName)); +} diff --git a/src_wearable/plugin-loading/plugin_container_support.h b/src_wearable/plugin-loading/plugin_container_support.h new file mode 100644 index 0000000..dbdf6c5 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_container_support.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_container_support.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ +#ifndef PLUGIN_CONTAINER_SUPPORT_H +#define PLUGIN_CONTAINER_SUPPORT_H + +#include +#include +#include + +#include +#include + +#include "plugin_model.h" + +class PluginContainerSupport +{ + public: + typedef std::list FeaturesList; + typedef std::list PluginsList; + + private: + // Standard features + typedef std::list StandardFeatureList; + + // Main feature list. Always equal to DB feature list + typedef std::set FeatureModelContainer; + + // Main plugin list. Always equal to DB plugin list + typedef std::set PluginModelsContainer; + + WrtDB::PluginHandleList m_rootPluginsList; + + PluginModelsContainer m_pluginModels; + + FeatureModelContainer m_featureModels; + + bool m_initialized; + + int m_widgetHandle; + + private: + // Reading + void readRootPluginsList(); + + // Plugin models + typedef std::multimap DeviceCapList; + void registerFeatureModel(WrtDB::FeatureHandle handle, + WrtDB::FeatureData* data, + DeviceCapList deviceCapabilities); + + WrtDB::FeatureModelPtr getFeatureModel(const std::string &name) const; + WrtDB::FeatureModelPtr getFeatureModel(WrtDB::FeatureHandle handle) const; + + PluginModelPtr getPluginModel(const WrtDB::FeatureModelPtr &feature) const; + + public: + PluginContainerSupport(); + + bool isInitialized() + { + return m_initialized; + } + bool isInitialized(int widgetHandle) + { + return (m_initialized && m_widgetHandle == widgetHandle); + } + void Initialize(int widgetHandle); + void registerPluginModel(WrtDB::DbPluginHandle handle); + std::list getAllowedFeatures(int widgetHandle) const; + void readAllowedPlugins(int widgetHandle); + void readRootPlugins(int widgetHandle); + PluginsList getRootPlugins() const; + PluginsList getPluginsList() const; + + PluginModelPtr getPluginForFeature(const std::string& featureName); + + PluginModelPtr getPluginModelById(WrtDB::DbPluginHandle handle) const; + + ~PluginContainerSupport(); +}; + +typedef std::shared_ptr PluginContainerSupportPtr; + +#endif // PLUGIN_CONTAINER_SUPPORT_H diff --git a/src_wearable/plugin-loading/plugin_iframe_support.cpp b/src_wearable/plugin-loading/plugin_iframe_support.cpp new file mode 100644 index 0000000..4e428dd --- /dev/null +++ b/src_wearable/plugin-loading/plugin_iframe_support.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_iframe_support.cpp + * @version 1.0 + * @brief + */ + +#include "plugin_iframe_support.h" + +#include +#include +#include + +void IframesSupport::registerDeclaration( + const JSObjectDeclarationPtr& declaration) +{ + _D("Registration iframes-supported plugins %s", declaration->getName().c_str()); + + if (declaration->getParentName().find('.') != std::string::npos) { + _E("The object will not be loaded to iframes"); + return; + } + m_iframesObjects.push_back(declaration); +} + +void IframesSupport::registerIframe(const JSObjectPtr& iframe) +{ + _D("LoadedIframes size: %d", m_loadedIframes.size() ); + + m_loadedIframes.insert(iframe); +} + +void IframesSupport::unregisterIframe(const JSObjectPtr& iframe) +{ + _D("LoadedIframes size: %d", m_loadedIframes.size() ); + + auto it_loaded = std::find_if(m_loadedIframes.begin(), + m_loadedIframes.end(), + std::bind2nd(EqualToJSObjectPtr(), iframe)); + //object not found, so thats the new iframe + if (it_loaded == m_loadedIframes.end()) { + _D("Nothing to unregister"); + return; + } + + m_loadedIframes.erase(it_loaded); +} + +bool IframesSupport::hasIframes() const +{ + return !m_loadedIframes.empty(); +} + +IframesSupport::DeclarationsList IframesSupport::getIframeObjects() const +{ + return m_iframesObjects; +} + +void IframesSupport::clean() +{ + m_iframesObjects.clear(); + m_loadedIframes.clear(); +} diff --git a/src_wearable/plugin-loading/plugin_iframe_support.h b/src_wearable/plugin-loading/plugin_iframe_support.h new file mode 100644 index 0000000..0c98768 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_iframe_support.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_iframe_support.h + * @version 1.0 + * @brief + */ + +#ifndef _WRTENGINE_SRC_PLUGINSERVICE_IFRAME_SUPPORT_H_ +#define _WRTENGINE_SRC_PLUGINSERVICE_IFRAME_SUPPORT_H_ + +#include +#include +#include +#include +#include "javascript_interface.h" + +class IframesSupport +{ + public: + typedef std::list DeclarationsList; + + public: + void registerDeclaration(const JSObjectDeclarationPtr& declaration); + + void registerIframe(const JSObjectPtr& iframe); + + void unregisterIframe(const JSObjectPtr& iframe); + + DeclarationsList getIframeObjects() const; + + bool hasIframes() const; + + void clean(); + + private: + std::list m_iframesObjects; + std::set m_loadedIframes; + + // used to find matching object from m_loadedIframes + struct EqualToJSObjectPtr + { + typedef JSObjectPtr first_argument_type; + typedef JSObjectPtr second_argument_type; + typedef bool result_type; + + result_type operator()(const first_argument_type &s1, + const second_argument_type &s2) const + { + return (s1->getObject() == s2->getObject()); + } + }; +}; + +#endif diff --git a/src_wearable/plugin-loading/plugin_logic.cpp b/src_wearable/plugin-loading/plugin_logic.cpp new file mode 100644 index 0000000..8458501 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_logic.cpp @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_logic.cpp + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and + * feature loading routines + * @brief This code is intended to work behind view controller + */ + +#include "plugin_logic.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "explorer.h" +#include "plugin.h" +#include "plugin_model.h" +#include "javascript_interface.h" +#include "js_function_manager.h" +#include "plugin_container_support.h" + +#include "js_page_session.h" + +using namespace std; +using namespace WrtDB; +using namespace WrtPlugins::W3C; + +namespace { +const char *LIBRARY_PATH_SEPARATOR = "/"; +} + +class PluginLogic::Impl +{ + PluginContainerSupportPtr m_pluginsSupport; + + typedef std::map PagesSessionsSet; + PagesSessionsSet m_sessions; + unsigned int m_windowHandle; + + public: + Impl(); + ~Impl(); + + // Widget session + void initSession(int widgetHandle); + void startSession(int widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(JSGlobalContextRef context); + + void performLibrariesUnload(); + + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void setCustomProperties(JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(JSGlobalContextRef ctx, + CustomEventType eventType, + void* data); + + unsigned int windowHandle() const; + void setWindowHandle(unsigned int handle); + + static bool s_sanityCheck; +}; + +IMPLEMENT_SINGLETON(PluginLogic); + +bool PluginLogic::Impl::s_sanityCheck = false; + +#define PLUGIN_LOGIC_SANITY_CHECK \ + if (!s_sanityCheck) \ + { \ + _E("Object is not available. Wrong flow occured"); \ + return; \ + } + +PluginLogic::Impl::Impl() : + m_windowHandle(0) +{ + s_sanityCheck = true; + + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS"); + _D("Initializing Plugin Logic..."); + m_pluginsSupport = PluginContainerSupportPtr(new PluginContainerSupport()); + + // explicit call to keep singleton's lifetime until calling destructor. + JsFunctionManagerSingleton::Instance(); + JavaScriptInterfaceSingleton::Instance(); +} + +PluginLogic::Impl::~Impl() +{ + _D("called"); + + s_sanityCheck = false; + + FOREACH(it, m_sessions) + { + _W("Must stop widget session before exit!"); + it->second->stopSession(); + } +} + +void PluginLogic::initSession(int widgetHandle) +{ + m_impl->initSession(widgetHandle); +} + +void PluginLogic::startSession(int widgetHandle, + JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme); +} + +void PluginLogic::stopSession(JSGlobalContextRef context) +{ + m_impl->stopSession(context); +} + +void PluginLogic::performLibrariesUnload() +{ + _W("This function is DEPRECATED"); + // m_impl->performLibrariesUnload(); +} + +bool PluginLogic::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context); +} + +void PluginLogic::loadPluginsIntoIframes(JSGlobalContextRef /*context*/) +{ + _W("This function is DEPRECATED"); +} + +void PluginLogic::setCustomProperties(double /*scaleFactor*/, + const char* /*encodedBundle*/, + const char* /*theme*/) +{ + _W("This function is DEPRECATED"); +} + +void PluginLogic::setCustomProperties(JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->setCustomProperties(context, scaleFactor, encodedBundle, theme); +} + +void PluginLogic::dispatchJavaScriptEvent(CustomEventType /*eventType*/) +{ + _W("This function is DEPRECATED"); +} + +void PluginLogic::dispatchJavaScriptEvent(JSGlobalContextRef context, + CustomEventType eventType, + void *data) +{ + m_impl->dispatchJavaScriptEvent(context, eventType, data); +} + +void PluginLogic::loadFrame(JSGlobalContextRef context) +{ + m_impl->loadFrame(context); +} + +void PluginLogic::unloadFrame(JSGlobalContextRef context) +{ + m_impl->unloadFrame(context); +} + +unsigned int PluginLogic::windowHandle() const +{ + return m_impl->windowHandle(); +} + +void PluginLogic::setWindowHandle(unsigned int handle) +{ + m_impl->setWindowHandle(handle); +} + +PluginLogic::PluginLogic() : m_impl(new PluginLogic::Impl()) +{} + +PluginLogic::~PluginLogic() +{} + +void PluginLogic::Impl::initSession(int widgetHandle) +{ + _D(">---------------------[init session START]---------------------<"); + + m_pluginsSupport->Initialize(widgetHandle); + PluginContainerSupport::PluginsList rootPluginList = + m_pluginsSupport->getRootPlugins(); + + FOREACH(it, rootPluginList) + { + PluginModelPtr& pluginModel = *it; + PluginPtr pluginLib = pluginModel->LibraryInstance.Get(); + + if (!pluginLib) { + std::string path = pluginModel->LibraryPath.Get() + + std::string(LIBRARY_PATH_SEPARATOR) + + pluginModel->LibraryName.Get(); + + pluginLib = Plugin::LoadFromFile(path); + + if (!pluginLib) { + _W("Loading library failed"); + } else { + pluginModel->LibraryInstance.Set(pluginLib); + _D("pluginModel->LibraryInstance.Set() : %s", + pluginLib->GetFileName().c_str()); + } + } else { + _D("Already loaded"); + } + } + _D("========== init session END =========="); +} + +void PluginLogic::Impl::startSession(int widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + _D("========== start session START =========="); + + if (!m_pluginsSupport->isInitialized(widgetHandle)) { + m_pluginsSupport->Initialize(widgetHandle); + } + auto sessionIt = m_sessions.find(context); + + // Check if corresponding session if not already created + if (sessionIt != m_sessions.end()) { + _W("Session already started!"); + } else { + auto newSession = JSPageSessionPtr(new JSPageSession(m_pluginsSupport)); + newSession->startSession(widgetHandle, + context, + scaleFactor, + encodedBundle, + theme); + + m_sessions[context] = newSession; + } + _D("========== start session END =========="); +} + +void PluginLogic::Impl::stopSession(JSGlobalContextRef context) +{ + _D("========== stop session START =========="); + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + } else { + sessionIt->second->stopSession(); + m_sessions.erase(sessionIt); + } + _D("========== stop session END =========="); +} + +bool PluginLogic::Impl::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context + ) +{ + _D("========== load ondemand plugin =========="); + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + return false; + } + + return sessionIt->second->loadPluginOnDemand(pluginHandle, + parentObject, + context); +} + +void PluginLogic::Impl::loadFrame(JSGlobalContextRef context) +{ + _D("========== load frame START =========="); + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + } else { + sessionIt->second->loadFrame(context); + } + _D("========== load frame END =========="); +} + +void PluginLogic::Impl::unloadFrame(JSGlobalContextRef context) +{ + _D("========== unload frame START =========="); + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + LogWarning("Session not exist!"); + } else { + sessionIt->second->unloadFrame(context); + + // I don't know why this session should be removed here. + // session list is removed also from stopSession(). + //m_sessions.erase(sessionIt); + } + _D("========== unload frame END =========="); +} + +void PluginLogic::Impl::setCustomProperties(JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + return; + } + + sessionIt->second->setCustomProperties(scaleFactor, + encodedBundle, + theme); +} + +void PluginLogic::Impl::dispatchJavaScriptEvent(JSGlobalContextRef context, + CustomEventType eventType, + void* data) +{ + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + _W("Session not exist!"); + return; + } + + sessionIt->second->dispatchJavaScriptEvent(eventType, data); +} + +unsigned int PluginLogic::Impl::windowHandle() const +{ + if (!s_sanityCheck) { + LogError("Object is not available. Wrong flow occured"); + } + return m_windowHandle; +} + +void PluginLogic::Impl::setWindowHandle(unsigned int handle) +{ + PLUGIN_LOGIC_SANITY_CHECK + m_windowHandle = handle; +} diff --git a/src_wearable/plugin-loading/plugin_logic.h b/src_wearable/plugin-loading/plugin_logic.h new file mode 100644 index 0000000..fb965c5 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_logic.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_logic.h + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and feature + * loading routines + * @brief This code is intended to work behind view controller + */ +#ifndef PLUGIN_LOGIC_H +#define PLUGIN_LOGIC_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace WrtPlugins::W3C; + +class PluginLogic : DPL::Noncopyable +{ + public: + // Widget session + void initSession(int widgetHandle); + void startSession(int widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(JSGlobalContextRef context); + + //TODO im not sure if it is needed. I think it should be hidden + void performLibrariesUnload(); + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + WRT_PLUGINS_DEPRECATED void loadPluginsIntoIframes( + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + // reset custom window properties. (Tizen requirements) + WRT_PLUGINS_DEPRECATED void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void setCustomProperties(JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + WRT_PLUGINS_DEPRECATED void dispatchJavaScriptEvent( + CustomEventType eventType); + + void dispatchJavaScriptEvent(JSGlobalContextRef ctx, + CustomEventType eventType, + void* data); + + unsigned int windowHandle() const; + void setWindowHandle(unsigned int handle); + + private: + PluginLogic(); + ~PluginLogic(); + + class Impl; + std::unique_ptr m_impl; + + friend class DPL::Singleton; +}; + +typedef DPL::Singleton PluginLogicSingleton; + +#endif // PLUGIN_LOGIC_H diff --git a/src_wearable/plugin-loading/plugin_model.cpp b/src_wearable/plugin-loading/plugin_model.cpp new file mode 100644 index 0000000..ee6dd6f --- /dev/null +++ b/src_wearable/plugin-loading/plugin_model.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_model.cpp + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief This file contains PluginModel, PluginHandle definitions. + */ + +#include "plugin_model.h" +#include +#include + +using namespace WrtDB; + +template +struct BindToPluginDAO : + DPL::Event::BindToDAO +{}; + +template +struct BindToFeatureDAOStatic : + DPL::Event::BindToDAO_Static +{}; + +PluginModel::PluginModel(const WrtDB::DbPluginHandle& handle) : + Handle(this, handle), + LibraryName(this, + BindToPluginDAO::Get), + LibraryPath(this, + BindToPluginDAO::Get), + FeatureHandles(this, + BindToFeatureDAOStatic:: + Get), + LibraryDependencies(this, + BindToPluginDAO::Get), + LibraryInstance(this, PluginPtr()) +{} + +WrtDB::DbPluginHandle PluginModel::getHandle() const +{ + return Handle.Get(); +} diff --git a/src_wearable/plugin-loading/plugin_model.h b/src_wearable/plugin-loading/plugin_model.h new file mode 100644 index 0000000..e834cd1 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_model.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_model.h + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief This file contains PluginModel, PluginHandle definitions. + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_PLUGIN_MODEL_H_ +#define WRT_SRC_PLUGIN_SERVICE_PLUGIN_MODEL_H_ + +#include +#include +#include +#include +#include + +#include +#include +#include + +class PluginModel; + +class PluginModel : public DPL::Event::Model +{ + public: + + /** + * *@brief Plugin handle + */ + DPL::Event::Property Handle; + + /** + * *@brief LibraryName + */ + DPL::Event::Property LibraryName; + + /** + * *@brief Library Path + */ + DPL::Event::Property LibraryPath; + + /** + * *@brief Feature set + */ + DPL::Event::Property + FeatureHandles; + + /** + * *@brief Librarydepencies + */ + DPL::Event::Property + LibraryDependencies; + + /** + * *@brief Library instance Low Level + * */ + DPL::Event::Property LibraryInstance; + + public: + PluginModel(const WrtDB::DbPluginHandle& handle); + + private: + WrtDB::DbPluginHandle getHandle() const; +}; + +typedef DPL::SharedPtr PluginModelPtr; + +#endif diff --git a/src_wearable/plugin-loading/plugin_property_support.cpp b/src_wearable/plugin-loading/plugin_property_support.cpp new file mode 100644 index 0000000..7b9d9b6 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_property_support.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_property_support.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 1.0 + * @brief + */ + +#include "plugin_property_support.h" +#include + +using namespace PluginModule; + +const char *NAVIGATOR_PROPERTY_NAME = "navigator"; +const char *SCALE_PROPERTY_NAME = "scale"; +const char *BUNDLE_PROPERTY_NAME = "__bundle"; +const char *THEME_PROPERTY_NAME = "theme"; + +WindowPropertySupport::WindowPropertySupport( + JSGlobalContextRef context) : + m_scale(0), + m_bundle(""), + m_theme(""), + m_context(context) +{} + +WindowPropertySupport::~WindowPropertySupport() +{} + +float WindowPropertySupport::getScale() const +{ + return m_scale; +} + +std::string WindowPropertySupport::getBundle() const +{ + return m_bundle; +} + +std::string WindowPropertySupport::getTheme() const +{ + return m_theme; +} + +JSGlobalContextRef WindowPropertySupport::getJSContext() const +{ + return m_context; +} + +void WindowPropertySupport::setScaleToNavigatorProperty(const double scale) +{ + _D("set window.navigator.scale: %ld", scale); + m_scale = scale; + setPropertyToNavigator(SCALE_PROPERTY_NAME, + JSValueMakeNumber(m_context, scale)); +} + +void WindowPropertySupport::setBundleToWindowProperty(const char* bundle) +{ + _D("set window.__bundle: %s", bundle); + if (bundle) { + m_bundle = bundle; + JSStringRef bundleString = JSStringCreateWithUTF8CString(bundle); + setPropertyToWindow(BUNDLE_PROPERTY_NAME, + JSValueMakeString(m_context, bundleString)); + JSStringRelease(bundleString); + } +} + +void WindowPropertySupport::setThemeToNavigatorProperty(const char* theme) +{ + _D("set window.navigator.__theme: %s", theme); + if (theme) { + m_theme = theme; + JSStringRef themeString = JSStringCreateWithUTF8CString(theme); + setPropertyToNavigator(THEME_PROPERTY_NAME, + JSValueMakeString(m_context, themeString)); + JSStringRelease(themeString); + } +} + +void WindowPropertySupport::setPropertyToWindow(const char* propertyName, + JSValueRef jsValue) +{ + _D("et property to window : %s", propertyName); + if (propertyName) { + JSObjectRef globalObject = JSContextGetGlobalObject(m_context); + JSStringRef propertyNameString = + JSStringCreateWithUTF8CString(propertyName); + JSObjectSetProperty(m_context, + globalObject, + propertyNameString, + jsValue, + kJSPropertyAttributeNone, + NULL); + JSStringRelease(propertyNameString); + } +} + +void WindowPropertySupport::setPropertyToNavigator(const char* propertyName, + JSValueRef jsValue) +{ + _D("set property to navigator : %s", propertyName); + if (propertyName) { + JSObjectRef globalObject = JSContextGetGlobalObject(m_context); + + JSStringRef navigatorString = + JSStringCreateWithUTF8CString(NAVIGATOR_PROPERTY_NAME); + JSValueRef navigatorValue = JSObjectGetProperty(m_context, + globalObject, + navigatorString, + NULL); + + JSStringRef propertyNameString = + JSStringCreateWithUTF8CString(propertyName); + JSObjectSetProperty(m_context, + JSValueToObject(m_context, navigatorValue, NULL), + propertyNameString, + jsValue, + kJSPropertyAttributeNone, + NULL); + + JSStringRelease(propertyNameString); + JSStringRelease(navigatorString); + } +} + diff --git a/src_wearable/plugin-loading/plugin_property_support.h b/src_wearable/plugin-loading/plugin_property_support.h new file mode 100644 index 0000000..fc946c4 --- /dev/null +++ b/src_wearable/plugin-loading/plugin_property_support.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_property_support.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ +#define _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ + +#include +#include + +namespace PluginModule { +class WindowPropertySupport +{ + public: + float getScale() const; + std::string getBundle() const; + std::string getTheme() const; + JSGlobalContextRef getJSContext() const; + + void setScaleToNavigatorProperty(const double scale); + void setBundleToWindowProperty(const char* bundle); + void setThemeToNavigatorProperty(const char* theme); + + explicit WindowPropertySupport(JSGlobalContextRef m_context); + ~WindowPropertySupport(); + + private: + float m_scale; + std::string m_bundle; // string of base64 encoded bundle + std::string m_theme; + JSGlobalContextRef m_context; + + void setPropertyToWindow(const char* propertyName, JSValueRef jsValue); + void setPropertyToNavigator(const char* propertyName, JSValueRef jsValue); +}; +} // namespace PluginModule + +#endif // _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ diff --git a/src_wearable/plugins-api-support/CMakeLists.txt b/src_wearable/plugins-api-support/CMakeLists.txt new file mode 100644 index 0000000..7a67b5e --- /dev/null +++ b/src_wearable/plugins-api-support/CMakeLists.txt @@ -0,0 +1,70 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Grzegorz Krawczyk (g.krawczyk@samsung.com) +# @version 1.0 +# + +pkg_search_module(dpl REQUIRED dpl-efl) + +set(PLUGINS_API_SUPPORT_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/Plugin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Object.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ObjectFactory.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistration.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistry.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${dpl_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGINS_API_SUPPORT} SHARED + ${PLUGINS_API_SUPPORT_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_API_SUPPORT} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_API_SUPPORT} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_PLUGINS_API_SUPPORT} + ${dpl_LIBRARIES} +) + +INSTALL(TARGETS ${TARGET_PLUGINS_API_SUPPORT} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES + ${CMAKE_CURRENT_SOURCE_DIR}/ExportedApi.h + ${CMAKE_CURRENT_SOURCE_DIR}/Plugin.h + ${CMAKE_CURRENT_SOURCE_DIR}/IObject.h + ${CMAKE_CURRENT_SOURCE_DIR}/ObjectFactory.h + ${CMAKE_CURRENT_SOURCE_DIR}/CallbackSupport.h + ${CMAKE_CURRENT_SOURCE_DIR}/tuple.h + ${CMAKE_CURRENT_SOURCE_DIR}/PluginSignals.h + ${CMAKE_CURRENT_SOURCE_DIR}/SignalSignature.h + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistration.h + DESTINATION include/wrt-plugins-api-support) diff --git a/src_wearable/plugins-api-support/CallbackSupport.h b/src_wearable/plugins-api-support/CallbackSupport.h new file mode 100644 index 0000000..bcaa849 --- /dev/null +++ b/src_wearable/plugins-api-support/CallbackSupport.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file CallbackSupport.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_CALLBACK_SUPPORT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_CALLBACK_SUPPORT_H_ + +#include +#include +#include +#include + +namespace WrtPluginsApi { +template +class CallbackSupport +{ + public: + typedef typename Sig::Signature SlotSignature; + typedef typename Sig::Type SlotType; + typedef std::string GroupType; + typedef std::vector SlotList; + + void Connect(const GroupType& group, const SlotType& slot) + { + auto groupIt = m_slots.find(group); + if (m_slots.end() == groupIt) { + groupIt = m_slots.insert(std::make_pair(group, SlotList())).first; + } + groupIt->second.push_back(slot); + } + + void Disconnect(const GroupType& group) + { + m_slots.erase(group); + } + + template + void Invoke(const Args& ... args) + { + FOREACH(groupIt, m_slots) + { + FOREACH(slotIt, groupIt->second) + { + (*slotIt)(args ...); + } + } + } + + template + void InvokeGroup(const GroupType& group, const Args& ... args) + { + auto groupIt = m_slots.find(group); + + if (m_slots.end() != groupIt) { + FOREACH(slotIt, groupIt->second) + { + (*slotIt)(args ...); + } + } + } + + private: + std::map m_slots; +}; +} +#endif diff --git a/src_wearable/plugins-api-support/ExportedApi.h b/src_wearable/plugins-api-support/ExportedApi.h new file mode 100644 index 0000000..28886d0 --- /dev/null +++ b/src_wearable/plugins-api-support/ExportedApi.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file ExportedApi.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_EXPORTED_API_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_EXPORTED_API_H_ + +#include + +/** + * This file provides definition of entry point to the plugin's shared library + * used by wrt. + * + * Each plugin have to provide 1 symbol which is get by dlsym. + * The name of required symbol is specified by 'GetExportedSymbolName' function + * The type of this symbol is pointer to ExportedApi struct + * + * To allow access to your plugin, you have to: + * + * 1)define 3 functions: + * - Register, + * - Unregister, + * - GetProvidedFeatures + * (names are not important) + * + * 2)define global struct named "dll_api" and initialize it with above functions + * *Example: + * ExportedApi dll_api = {Register, Unregister, GetProvidedFeatures}; + * + * + * Detailed Example how the file with api may looks like file: + * + * #include + * #include + * + * #include + * #include + * #include + * #include + * + * #include "JSTest.h" + * #include "plugin_config.h" + * + * #define OBJECT_WIDGET "widget" + * #define OBJECT_TEST "__test" + * + * using namespace WrtPlugins::W3C; + * using namespace WrtDeviceApis; + * using namespace WrtDeviceApis::Commons; + * using namespace WrtPluginsApi; + * + * namespace W3CTest + * { + * + * void on_widget_start_callback(int widgetId) + * { + * + * } + * + * void on_widget_stop_callback(int widgetId) + * { + * } + * + * } + * + * void Register(PluginRegistration& r) + * { + * Plugin* plugin = new Plugin(); + * + * auto test = ObjectFactory::createMainObject( + * OBJECT_TEST, + * WrtPlugins::W3C::JSTest::getClassRef, + * OBJECT_WIDGET); + * + * plugin->AddObject(test); + * + * r.Connect(W3CTest::on_widget_start_callback); + * + * r.Connect(W3CTest::on_widget_stop_callback); + * + * r.AddPlugin(*plugin); + * } + * + * void Unregister(PluginRegistration& r, Plugin* plugin) + * { + * r.DisconnectAll(); + * delete plugin; + * } + * + * void GetProvidedFeatures(feature_mapping_interface_t *mapping) + * { + * WrtPlugins::W3C::WidgetTestDeclarations::getMappingInterface(mapping); + * } + * + * ExportedApi dll_api={Register, Unregister, GetProvidedFeatures}; + * + * #undef OBJECT_WIDGET + * #undef OBJECT_TEST + * + * + * */ + +//forward declaration +struct feature_mapping_interface_s; +typedef struct feature_mapping_interface_s feature_mapping_interface_t; + +extern "C" struct ExportedApi +{ + /* + * This function is invoked when library is loaded + * */ + void (*Register)(WrtPluginsApi::PluginRegistration&); + + /* + * This function is invoked when library is unloaded + * */ + void (*Unregister)(WrtPluginsApi::PluginRegistration&, + WrtPluginsApi::Plugin* plugin); + + /* + * This function is invoked by wrt-plugins-installer to obtain + * info about features,functions,objects provided by plugin + * */ + void (*GetProvidedFeatures)(feature_mapping_interface_t*); +}; + +constexpr const char* GetExportedSymbolName() +{ + return "dll_api"; +} + +#endif diff --git a/src_wearable/plugins-api-support/IObject.h b/src_wearable/plugins-api-support/IObject.h new file mode 100644 index 0000000..4148d91 --- /dev/null +++ b/src_wearable/plugins-api-support/IObject.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IObject.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_IOBJECT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_IOBJECT_H_ + +#include +#include + +extern "C" { +typedef struct OpaqueJSClass* (*ClassRef)(); +} + +namespace WrtPluginsApi { +enum class IObjectType +{ + Object, + Function, + Interface, + InterfaceInstance +}; + +enum class IObjectOption +{ + Overlayed +}; + +class IObject; +typedef std::shared_ptr IObjectPtr; + +class IObject +{ + public: + constexpr static const char* WINDOW_OBJECT() + { + return "window"; + } + + virtual void AddChild(const IObjectPtr&) = 0; + + /* + * Optional + * */ + virtual void setBoolOption(IObjectOption option, bool value) = 0; + + virtual ~IObject(){} +}; + +typedef std::list IObjectsList; +typedef std::shared_ptr IObjectsListPtr; +} +#endif diff --git a/src_wearable/plugins-api-support/IObject_cast.h b/src_wearable/plugins-api-support/IObject_cast.h new file mode 100644 index 0000000..105a31d --- /dev/null +++ b/src_wearable/plugins-api-support/IObject_cast.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IObject_cast.h + * @author + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGINS_API_SUPPORT_CAST_H_ +#define _WRT_PLUGINS_COMMON_PLUGINS_API_SUPPORT_CAST_H_ + +#include +#include +#include + +namespace WrtPluginsApi { +inline ObjectPtr CAST(const IObjectPtr& object) +{ + return std::dynamic_pointer_cast(object); +} +} +#endif diff --git a/src_wearable/plugins-api-support/Object.cpp b/src_wearable/plugins-api-support/Object.cpp new file mode 100644 index 0000000..7db93e4 --- /dev/null +++ b/src_wearable/plugins-api-support/Object.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Object.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "Object.h" + +namespace WrtPluginsApi { +void Object::AddChild(const IObjectPtr& child) +{ + if (!m_children) { + m_children = IObjectsListPtr(new IObjectsList); + } + m_children->push_back(child); +} + +void Object::setBoolOption(IObjectOption option, bool value) +{ + if (!m_options) { + m_options = ObjectOptionPtr(new ObjectOption); + } + + switch (option) { + case IObjectOption::Overlayed: + m_options->overlayedMode = value; + break; + default: + break; + } +} + +IObjectsListPtr Object::GetChildren() const +{ + return m_children; +} + +ClassRef Object::GetClass() const +{ + return m_classRef; +} + +ClassRef Object::GetClassConstructor() const +{ + return m_constructorRef; +} + +const char* Object::GetInterfaceName() const +{ + return m_interfaceName; +} + +const char* Object::GetName() const +{ + return m_name; +} + +IObjectType Object::GetType() const +{ + return m_type; +} + +const char* Object::GetParentName() const +{ + return m_parentName; +} + +ObjectOptionPtr Object::GetOptions() const +{ + return m_options; +} + +Object::Object(const char* name, + ClassRef ref, + IObjectType type) : + m_name(name), + m_classRef(ref), + m_parentName(0), + m_type(type), + m_interfaceRef(0), + m_interfaceName(0), + m_constructorRef(0) +{} + +Object::Object(const char* name, + ClassRef ref, + const char* parentName, + IObjectType type) : + m_name(name), + m_classRef(ref), + m_parentName(parentName), + m_type(type), + m_interfaceRef(0), + m_interfaceName(0), + m_constructorRef(0) +{} + +Object::Object(const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName, + IObjectType type) : + m_name(name), + m_parentName(parentName), + m_type(type), + m_interfaceRef(interfaceRef), + m_interfaceName(interfaceName), + m_constructorRef(constructorRef) +{} + +Object::~Object() +{} +} diff --git a/src_wearable/plugins-api-support/Object.h b/src_wearable/plugins-api-support/Object.h new file mode 100644 index 0000000..268a27f --- /dev/null +++ b/src_wearable/plugins-api-support/Object.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IObject.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_H_ + +#include +#include + +#include +#include + +namespace WrtPluginsApi { +class Object; +typedef std::shared_ptr ObjectPtr; + +struct ObjectOption +{ + DPL::OptionalBool overlayedMode; +}; +typedef std::shared_ptr ObjectOptionPtr; + +class Object : public IObject +{ + public: + Object(const char* name, + ClassRef ref, + IObjectType type = IObjectType::Object); + + Object(const char* name, + ClassRef ref, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + + Object(const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + + ~Object(); + + void AddChild(const IObjectPtr&); + + void setBoolOption(IObjectOption option, bool value); + + IObjectsListPtr GetChildren() const; + + ClassRef GetClass() const; + + /* + * Available only for object with type InterfaceInstance + * */ + ClassRef GetClassConstructor() const; + + const char* GetInterfaceName() const; + + const char* GetName() const; + + IObjectType GetType() const; + + const char* GetParentName() const; + + ObjectOptionPtr GetOptions() const; + + private: + const char* m_name; + ClassRef m_classRef; + + const char* m_parentName; + + IObjectType m_type; + + ClassRef m_interfaceRef; + const char* m_interfaceName; + ClassRef m_constructorRef; + + ObjectOptionPtr m_options; + + IObjectsListPtr m_children; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/ObjectFactory.cpp b/src_wearable/plugins-api-support/ObjectFactory.cpp new file mode 100644 index 0000000..b897399 --- /dev/null +++ b/src_wearable/plugins-api-support/ObjectFactory.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file ObjectFactory.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "ObjectFactory.h" +#include "Object.h" + +namespace WrtPluginsApi { +namespace ObjectFactory { +IObjectPtr createObject( + const char* name, + ClassRef ref, + IObjectType type) +{ + return IObjectPtr(new Object(name, ref, type)); +} + +IObjectPtr createMainObject( + const char* name, + ClassRef ref, + const char* parentName, + IObjectType type) +{ + return IObjectPtr(new Object(name, ref, parentName, type)); +} + +IObjectPtr createObjectWithInterface( + const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName, + IObjectType type) +{ + return IObjectPtr(new Object(name, + interfaceRef, + interfaceName, + constructorRef, + parentName, + type)); +} +} +} diff --git a/src_wearable/plugins-api-support/ObjectFactory.h b/src_wearable/plugins-api-support/ObjectFactory.h new file mode 100644 index 0000000..59bff1d --- /dev/null +++ b/src_wearable/plugins-api-support/ObjectFactory.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file ObjectFactory.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_FACTORY_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_FACTORY_H_ + +#include +#include + +namespace WrtPluginsApi { +namespace ObjectFactory { +IObjectPtr createObject( + const char* name, + ClassRef ref, + IObjectType type = IObjectType::Object); + +IObjectPtr createMainObject( + const char* name, + ClassRef ref, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + +IObjectPtr createObjectWithInterface( + const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); +} +} +#endif diff --git a/src_wearable/plugins-api-support/Plugin.cpp b/src_wearable/plugins-api-support/Plugin.cpp new file mode 100644 index 0000000..6303c32 --- /dev/null +++ b/src_wearable/plugins-api-support/Plugin.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Plugin.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include "Plugin.h" + +namespace WrtPluginsApi { +void Plugin::AddObject(const IObjectPtr& object) +{ + m_objects->push_back(object); +} + +IObjectsListPtr Plugin::GetObjects() const +{ + return m_objects; +} + +Plugin::~Plugin() +{} + +Plugin::Plugin() : m_objects(new IObjectsList()) +{} +} diff --git a/src_wearable/plugins-api-support/Plugin.h b/src_wearable/plugins-api-support/Plugin.h new file mode 100644 index 0000000..5458714 --- /dev/null +++ b/src_wearable/plugins-api-support/Plugin.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file Plugin.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_H_ + +#include +#include + +namespace WrtPluginsApi { +class Plugin +{ + public: + void AddObject(const IObjectPtr& object); + + IObjectsListPtr GetObjects() const; + + Plugin(); + + virtual ~Plugin(); + + private: + IObjectsListPtr m_objects; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/PluginRegistration.cpp b/src_wearable/plugins-api-support/PluginRegistration.cpp new file mode 100644 index 0000000..4418e32 --- /dev/null +++ b/src_wearable/plugins-api-support/PluginRegistration.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistration.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "PluginRegistration.h" + +#include "PluginRegistrationImpl.h" +#include "Plugin.h" +#include + +namespace WrtPluginsApi { +PluginRegistration::PluginRegistration(Impl* impl) : m_impl(impl) +{ + AssertMsg(impl != 0, "impl is NULL"); +} + +template +void PluginRegistration::Connect(const typename SignalSignature::Type& slot) +{ + m_impl->Connect(slot); +} + +void PluginRegistration::DisconnectAll() +{ + m_impl->DisconnectAll(); +} + +void PluginRegistration::AddPlugin(Plugin& plugin) +{ + m_impl->AddPlugin(plugin); +} + +#define EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(SignalSignature) \ + template void PluginRegistration::Connect( \ + const typename SignalSignature::Type &) + +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnWidgetStart); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnWidgetStop); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnFrameLoad); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnFrameUnload); +} diff --git a/src_wearable/plugins-api-support/PluginRegistration.h b/src_wearable/plugins-api-support/PluginRegistration.h new file mode 100644 index 0000000..e871a76 --- /dev/null +++ b/src_wearable/plugins-api-support/PluginRegistration.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistration.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_H_ + +#include +#include "Plugin.h" +#include "PluginSignals.h" + +namespace WrtPluginsApi { +class PluginRegistration +{ + public: + class Impl; + + explicit PluginRegistration(PluginRegistration::Impl* impl); + + template + void Connect(const typename SignalSignature::Type& slot); + + void DisconnectAll(); + + void AddPlugin(Plugin& plugin); + + private: + std::unique_ptr m_impl; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/PluginRegistrationImpl.h b/src_wearable/plugins-api-support/PluginRegistrationImpl.h new file mode 100644 index 0000000..1c17859 --- /dev/null +++ b/src_wearable/plugins-api-support/PluginRegistrationImpl.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistrationImpl.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_IMPL_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_IMPL_H_ + +#include +#include "SignalsSupport.h" +#include "Plugin.h" +#include + +namespace WrtPluginsApi { +class PluginRegistration::Impl +{ + public: + Impl(SignalsSupport& registry, const std::string& libraryName) : + m_registry(registry), + m_libraryName(libraryName) + {} + + void AddPlugin(Plugin& plugin) + { + m_registry.AddPlugin(m_libraryName, plugin); + } + + template + void Connect(const typename T::Type& slot) + { + m_registry.Connect(m_libraryName, slot); + } + + void DisconnectAll() + { + m_registry.Disconnect(m_libraryName); + } + + private: + SignalsSupport& m_registry; + std::string m_libraryName; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/PluginRegistry.cpp b/src_wearable/plugins-api-support/PluginRegistry.cpp new file mode 100644 index 0000000..c4bc496 --- /dev/null +++ b/src_wearable/plugins-api-support/PluginRegistry.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include "PluginRegistry.h" +#include "PluginRegistration.h" +#include "PluginRegistrationImpl.h" +#include "ExportedApi.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace WrtPluginsApi { +void PluginRegistry::AddPlugin(const std::string& libraryName, + Plugin& plugin) +{ + LogDebug("Adding plugin for library: " << libraryName); + + auto libraryIt = m_plugins.find(libraryName); + if (m_plugins.end() == libraryIt) { + m_plugins[libraryName] = &plugin; + } +} + +Plugin* PluginRegistry::GetPlugin(const std::string& libraryName) +{ + auto it = m_plugins.find(libraryName); + if (it == m_plugins.end()) { + if (!LoadFromFile(libraryName)) { + LogError("Failed to load lib" << libraryName); + ThrowMsg(PluginNotFound, "Failed to load plugin"); + } + + return m_plugins[libraryName]; + } + + return it->second; +} + +void PluginRegistry::RemovePlugin(const std::string& libraryName, + Plugin& plugin) +{ + auto it = m_plugins.find(libraryName); + if (it != m_plugins.end()) { + if (&plugin == it->second) { + m_plugins.erase(it); + } + } +} + +void PluginRegistry::UnloadAll() +{ + LogDebug("Unload all plugins"); + + typedef void (*UnregisterFunction)(PluginRegistration&, Plugin&); + + FOREACH(libraryIt, m_libraries) + { + auto pluginIt = m_plugins.find(libraryIt->first); + if (m_plugins.end() != pluginIt) { + void* handle = dlopen(libraryIt->first.c_str(), RTLD_NOW); + if (!handle) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + continue; + } + DPL_SCOPE_EXIT(handle) { + if (dlclose(handle) != 0) { + const char* error = dlerror(); + if (error != NULL) + { + std::string errstr{error}; + _E("%s", errstr.c_str()); + } + else + { + _E("unknown error while closing plug-in library"); + } + } + }; + + ExportedApi* entryPoint = + static_cast + (dlsym(handle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + continue; + } + if (entryPoint->Unregister == NULL) { + LogError("Error Unregister function not set"); + continue; + } + + PluginRegistration registration( + new PluginRegistration::Impl(*this, libraryIt->first)); + + entryPoint->Unregister(registration, (pluginIt->second)); + + m_plugins.erase(pluginIt); + } + dlclose(libraryIt->second); + } +} + +bool PluginRegistry::LoadFromFile(const std::string& libraryName) +{ + void* handle = dlopen(libraryName.c_str(), RTLD_NOW); + if (!handle) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + return false; + } + m_libraries[libraryName] = handle; + + ExportedApi* entryPoint = + static_cast(dlsym(handle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + return false; + } + + if (entryPoint->Register == NULL) { + LogError("Error Register function not set"); + return false; + } + if (entryPoint->Unregister == NULL) { + LogError("Error Unregister function not set"); + return false; + } + + PluginRegistration registration( + new PluginRegistration::Impl(*this, libraryName)); + entryPoint->Register(registration); + + return true; +} + +PluginRegistry::~PluginRegistry() +{ + //TODO discuss ... when the unload should be called + // UnloadAll(); +} +} diff --git a/src_wearable/plugins-api-support/PluginRegistry.h b/src_wearable/plugins-api-support/PluginRegistry.h new file mode 100644 index 0000000..5db1ea4 --- /dev/null +++ b/src_wearable/plugins-api-support/PluginRegistry.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_LOADING_PLUGIN_REGISTRY_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_LOADING_PLUGIN_REGISTRY_H_ + +#include +#include +#include "SignalsSupport.h" +#include "Plugin.h" +#include + +namespace WrtPluginsApi { +typedef std::list PluginsList; +typedef std::shared_ptr PluginsListPtr; +typedef std::map< std::string, PluginsListPtr> PluginsSet; + +class PluginRegistry : public SignalsSupport +{ + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, PluginNotFound) + + template + void Call(Args ... args) + { + Invoke(args ...); + } + + template + void CallGroup(const typename CallbackSupport::GroupType& type, + Args ... args) + { + InvokeGroup(type, args ...); + } + + void AddPlugin(const std::string& libraryName, Plugin& plugin); + + /* + * @throw PluginNotFound + * */ + Plugin* GetPlugin(const std::string& libraryName); + + void RemovePlugin(const std::string& libraryName, Plugin& plugin); + + void UnloadAll(); + + ~PluginRegistry(); + + private: + bool LoadFromFile(const std::string& libraryName); + + typedef void* Symbol; + + std::map m_plugins; + std::map m_libraries; +}; + +typedef std::shared_ptr PluginRegistryPtr; +} + +#endif diff --git a/src_wearable/plugins-api-support/PluginSignals.h b/src_wearable/plugins-api-support/PluginSignals.h new file mode 100644 index 0000000..556d620 --- /dev/null +++ b/src_wearable/plugins-api-support/PluginSignals.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file PluginSignals.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_SIGNALS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_SIGNALS_H_ + +#include "SignalSignature.h" + +namespace WrtPluginsApi { +struct OnWidgetStart : SignalSignature {}; + +struct OnWidgetStop : SignalSignature {}; + +struct OnFrameLoad : SignalSignature {}; + +struct OnFrameUnload : SignalSignature {}; +} + +#endif diff --git a/src_wearable/plugins-api-support/SignalSignature.h b/src_wearable/plugins-api-support/SignalSignature.h new file mode 100644 index 0000000..b43747e --- /dev/null +++ b/src_wearable/plugins-api-support/SignalSignature.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file SignalSignature.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNAL_SIGNATURE_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNAL_SIGNATURE_H_ + +#include + +namespace WrtPluginsApi { +template struct SignalSignature; + +template +struct SignalSignature +{ + typedef R (*Signature)(Args ...); + typedef std::function Type; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/SignalsSupport.h b/src_wearable/plugins-api-support/SignalsSupport.h new file mode 100644 index 0000000..9c47af2 --- /dev/null +++ b/src_wearable/plugins-api-support/SignalsSupport.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file IPluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNALS_SUPPORT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNALS_SUPPORT_H_ + +#include +#include +#include "CallbackSupport.h" +#include "tuple.h" +#include "PluginSignals.h" +#include "Plugin.h" + +namespace WrtPluginsApi { +class SignalsSupport +{ + public: + virtual ~SignalsSupport() {} + + template + void Connect(const std::string& libraryName, const typename T::Type& slot) + { + Tuple::get_by_type >(m_slots).Connect(libraryName, + slot); + } + + void Disconnect(const std::string& libraryName) + { + DisconnectGroup(m_slots, libraryName); + } + + virtual void AddPlugin(const std::string& libraryName, Plugin& plugin) = 0; + + protected: + template + void Invoke(const Args& ... args) + { + Tuple::get_by_type >(m_slots).Invoke(args ...); + } + + template + void InvokeGroup(const std::string& libraryName, const Args& ... args) + { + Tuple::get_by_type >(m_slots).InvokeGroup( + libraryName, + args ...); + } + + private: + template + void DisconnectSlot(std::tuple& slots, + const std::string& libraryName, + typename std::enable_if<(N >= 0)>::type* = NULL) + { + std::get(slots).Disconnect(libraryName); + DisconnectSlot(slots, libraryName); + } + + template + void DisconnectSlot(std::tuple& /*slots*/, + const std::string& /*libraryName*/, + typename std::enable_if<(N == -1)>::type* = NULL) + {} + + template + void DisconnectGroup(std::tuple& slots, + const std::string& libraryName) + { + DisconnectSlot(slots, libraryName); + } + + std::tuple, + CallbackSupport, + CallbackSupport, + CallbackSupport > m_slots; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/detail/traits.h b/src_wearable/plugins-api-support/detail/traits.h new file mode 100644 index 0000000..7ab56db --- /dev/null +++ b/src_wearable/plugins-api-support/detail/traits.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file traits.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_DETAIL_TRAITS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_DETAIL_TRAITS_H_ + +namespace WrtPluginsApi { +namespace Traits { +namespace Detail { +template +struct index_of_; + +/* + * CurrentArgType is not equal to RequiredType, check next tuple's argument + */ +template +struct index_of_ +{ + static const size_t value = index_of_::value; +}; + +/* + * RequiredType found on tuple's args list + * return position on tuple's list + */ +template +struct index_of_ +{ + static const size_t value = n; +}; + +/* + * RequiredType found on last position of tuple's args list + * return position on tuple's list + */ +template +struct index_of_ +{ + static const size_t value = n; +}; + +/* + * RequiredType was not found on tuple args list + */ +template +struct index_of_ +{ + static const size_t value = -1; +}; +} +} +} + +#endif diff --git a/src_wearable/plugins-api-support/js_types.h b/src_wearable/plugins-api-support/js_types.h new file mode 100644 index 0000000..387c5bc --- /dev/null +++ b/src_wearable/plugins-api-support/js_types.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file js_types.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#ifndef WRT_PLUGIN_COMMON_API_SUPPORT_JS_TYPES_H_ +#define WRT_PLUGIN_COMMON_API_SUPPORT_JS_TYPES_H_ + +#include + +//forward declaration +extern "C" { +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +namespace WrtPluginsApi { +struct JavaScriptObject +{ + JSObjectRef instance; + std::string name; +}; +} + +#endif diff --git a/src_wearable/plugins-api-support/traits.h b/src_wearable/plugins-api-support/traits.h new file mode 100644 index 0000000..286c510 --- /dev/null +++ b/src_wearable/plugins-api-support/traits.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file traits.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TRAITS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TRAITS_H_ + +#include "detail/traits.h" + +namespace WrtPluginsApi { +namespace Traits { +/** + * Gets index of specified type in the type list. + */ +template +struct index_of +{ + static const size_t value = Detail::index_of_<0, + RequiredType, + TupleArgTypes ...>::value; +}; +} +} + +#endif diff --git a/src_wearable/plugins-api-support/tuple.h b/src_wearable/plugins-api-support/tuple.h new file mode 100644 index 0000000..ec7c3b3 --- /dev/null +++ b/src_wearable/plugins-api-support/tuple.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file tuple.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TUPLE_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TUPLE_H_ + +#include +#include "traits.h" + +namespace WrtPluginsApi { +namespace Tuple { +template +T& get_by_type(std::tuple& tuple) +{ + return std::get::value>(tuple); +} +} +} + +#endif diff --git a/src_wearable/plugins-installer/CMakeLists.txt b/src_wearable/plugins-installer/CMakeLists.txt new file mode 100644 index 0000000..6c01a00 --- /dev/null +++ b/src_wearable/plugins-installer/CMakeLists.txt @@ -0,0 +1,69 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Andrzej Surdej (a.surdej@samsung.com) +# @version 1.0 +# + +SET(TARGET_PLUGINS_INSTALLER "wrt-plugins-installer") + +SET(WRT_PLUGINS_INSTALLER_SRC_DIR + ${CMAKE_CURRENT_SOURCE_DIR} +) + +PKG_CHECK_MODULES(PLUGINS_INSTALLER_DEPS + libxml-2.0 + cert-svc-vcore + dpl-efl + dpl-wrt-dao-rw + libpcrecpp + REQUIRED +) + +INCLUDE_DIRECTORIES( + ${WRT_PLUGINS_INSTALLER_SRC_DIR} + ${PLUGINS_INSTALLER_INCLUDES} + ${PLUGINS_INSTALLER_DEPS_INCLUDE_DIRS} + ${PLUGINS_API_SUPPORT_DIRS} +) + +SET(WRT_PLUGINS_INSTALLER_SOURCES + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/wrt_plugins_installer.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_installer.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_utils.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_objects.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_metafile_reader.cpp +) + +ADD_DEFINITIONS(${PLUGINS_INSTALLER_DEPS_CFLAGS}) +ADD_DEFINITIONS(${PLUGINS_INSTALLER_DEPS_CFLAGS_OTHERS}) + +ADD_EXECUTABLE(${TARGET_PLUGINS_INSTALLER} + ${WRT_PLUGINS_INSTALLER_SOURCES} +) + +TARGET_LINK_LIBRARIES(${TARGET_PLUGINS_INSTALLER} + ${PLUGINS_INSTALLER_DEPS_LIBRARIES} + ${TARGET_PLUGINS_API_SUPPORT} "-ldl" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_INSTALLER} PROPERTIES + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON +) + +INSTALL(TARGETS ${TARGET_PLUGINS_INSTALLER} DESTINATION bin) diff --git a/src_wearable/plugins-installer/DESCRIPTION b/src_wearable/plugins-installer/DESCRIPTION new file mode 100644 index 0000000..0e8c571 --- /dev/null +++ b/src_wearable/plugins-installer/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Widget (un)installer, plugin (un)installer diff --git a/src_wearable/plugins-installer/plugin_installer.cpp b/src_wearable/plugins-installer/plugin_installer.cpp new file mode 100644 index 0000000..c756931 --- /dev/null +++ b/src_wearable/plugins-installer/plugin_installer.cpp @@ -0,0 +1,710 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer.cpp + * @author Andrzej Surdej(a.surdej@samgsung.com) + * @version + * @brief + */ + +#include "plugin_installer.h" + +#include +#include +#include +#include + +#include +#include + +#include "plugin_objects.h" +#include "plugin_metafile_reader.h" +#include "plugin_installer_errors.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace WrtDB; +using namespace WrtPluginsApi; + +IMPLEMENT_SINGLETON(PluginsInstaller) + +namespace { +const std::string DIRECTORY_SEPARATOR = std::string("/"); +} + +const int PluginsInstaller::INSTALLATION_ERROR = -1; + +PluginsInstaller::PluginsInstaller() : + m_initialized(false) +{ + LogDebug("PluginsInstaller created."); +} +PluginsInstaller::~PluginsInstaller() +{ + LogDebug("PluginsInstaller destroyed."); +} + +void PluginsInstaller::checkDatabaseTablesExistance() +{ + if (!WrtDB::WrtDatabase::CheckTableExist("FeaturesList") || + !WrtDB::WrtDatabase::CheckTableExist("PluginProperties") || + !WrtDB::WrtDatabase::CheckTableExist("PluginDependencies") || + !WrtDB::WrtDatabase::CheckTableExist("PluginImplementedObjects") || + !WrtDB::WrtDatabase::CheckTableExist("PluginRequiredObjects") || + !WrtDB::WrtDatabase::CheckTableExist("DeviceCapabilities") || + !WrtDB::WrtDatabase::CheckTableExist("FeatureDeviceCapProxy")) + { + LogError("Wrong database. Required tables not exist."); + deinitialize(); + Assert(false && "Wrong database. Required tables not exist."); + } +} + +bool PluginsInstaller::initialize() +{ + LogDebug("Initializing required systems."); + + // Check paths + if (!PluginUtils::checkPaths()) { + return false; + } + // Initialize ValidationCore - this must be done before AttachDatabases + ValidationCore::VCoreInit( + std::string(GlobalConfig::GetFingerprintListFile()), + std::string(GlobalConfig::GetFingerprintListSchema()), + std::string(GlobalConfig::GetVCoreDatabaseFilePath())); + + xmlInitParser(); + WrtDB::WrtDatabase::attachToThreadRW(); + ValidationCore::AttachToThreadRW(); + checkDatabaseTablesExistance(); + LogDebug("Initialized."); + m_initialized = true; + return true; +} + +void PluginsInstaller::deinitialize() +{ + LogDebug("Shuting systems down."); + m_initialized = false; + ValidationCore::DetachFromThread(); + WrtDB::WrtDatabase::detachFromThread(); + ValidationCore::VCoreDeinit(); + xmlCleanupParser(); + LogDebug("Done"); +} + +PluginsInstaller::ReturnStatus PluginsInstaller::installPlugin( + const std::string& libPath) +{ + if (!m_initialized) { + LogError("Plugins installer not initialized."); + return ReturnStatus::NotInitialized; + } + LogDebug("Plugin installation started. Checking path: " << libPath); + + if (!PluginUtils::checkPath(libPath)) { + return ReturnStatus::WrongPluginPath; + } + + LogDebug("Plugin path ok. Searching for config file..."); + + std::string metaFileName = libPath + DIRECTORY_SEPARATOR + + std::string(WrtDB::GlobalConfig::GetPluginMetafileName()); + if (PluginUtils::checkFileExistance(metaFileName)) { + return installPluginFromMetafile(libPath, metaFileName); + } + + PluginMetafileData pluginInfo; + pluginInfo.m_libraryName = getLibraryName(libPath); + + LogDebug( + "Config file done. Lib name: " << pluginInfo.m_libraryName + << + ". Searching for installed plugin..."); + + if (WrtDB::PluginDAO::isPluginInstalled(pluginInfo.m_libraryName)) { + LogDebug("Plugin already installed."); + return ReturnStatus::AlreadyInstalled; + } + LogDebug("Plugin not installed. Loading library file..."); + + PluginObjectsPtr libraryObjects; + PluginHandle pluginHandle; + + std::string filename = libPath + DIRECTORY_SEPARATOR + + pluginInfo.m_libraryName; + + LogDebug("Loading plugin: " << filename); + + Plugin* plugin; + Try + { + plugin = m_registry.GetPlugin(filename); + } + Catch(DPL::Exception) { + LogError("Loading library failed " << filename); + return ReturnStatus::LoadingLibraryError; + } + libraryObjects = PluginObjectsPtr(new PluginObjects()); + + LogDebug("#####"); + LogDebug("##### Plugin: " << filename << " supports new plugin API"); + LogDebug("#####"); + + FOREACH(o, *plugin->GetObjects()) { + libraryObjects->addObjects(CAST(*o)->GetParentName(), + CAST(*o)->GetName()); + + LogDebug("[Parent << Object] " << CAST(*o)->GetParentName() + << " << " + << CAST(*o)->GetName()); + + registerObjects(libraryObjects, plugin->GetObjects()); + } + + if (!fillMappingInterfaces(pluginInfo, filename)) { + m_registry.RemovePlugin(filename, *plugin); + return ReturnStatus::LoadingLibraryError; + } + + LogDebug("Library loaded. Registering plugin..."); + + Try + { + pluginHandle = + PluginDAO::registerPlugin(pluginInfo, libPath); + + LogDebug("Plugin registered. Registering features..."); + + FOREACH(it, pluginInfo.m_featureContainer) + { + LogError("PluginHandle: " << pluginHandle); + FeatureDAO::RegisterFeature(*it, pluginHandle); + } + + LogDebug("Features registered. Registering objects..."); + + registerPluginObjects(pluginHandle, libraryObjects); + + LogDebug("Registration done. Resolving dependencies..."); + + //TODO: can it be replaced with resolvePluginDependencies(handle) + if (!registerAndUpdateInstallation(pluginHandle, libraryObjects)) { + return ReturnStatus::InstallationWaiting; + } + } Catch(DPL::Exception) { + LogError("Failed to make database entry."); + return ReturnStatus::DatabaseError; + } + + LogDebug("Plugin installed successfully."); + return ReturnStatus::Success; +} + +PluginObjectsPtr PluginsInstaller::loadLibraryFromMetafile( + const std::string& libName) const +{ + LogDebug("Loading library: " << libName); + + void *dlHandle = dlopen(libName.c_str(), RTLD_NOW); + if (dlHandle == NULL) { + const char* error = (const char*)dlerror(); + LogError( + "Failed to load plugin: " << libName << + ". Reason: " << (error != NULL ? error : "unknown")); + ThrowMsg(PluginInstall::Exceptions::LibraryException, "Library error"); + } + + const js_entity_definition_t *rawEntityList = NULL; + get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL; + + getWidgetEntityMapProcPtr = + reinterpret_cast(dlsym(dlHandle, + PLUGIN_GET_CLASS_MAP_PROC_NAME)); + + if (getWidgetEntityMapProcPtr) { + rawEntityList = (*getWidgetEntityMapProcPtr)(); + } else { + rawEntityList = + static_cast(dlsym(dlHandle, + PLUGIN_CLASS_MAP_NAME)); + } + + if (rawEntityList == NULL) { + dlclose(dlHandle); + LogError("Failed to read class name" << libName); + ThrowMsg(PluginInstall::Exceptions::LibraryException, "Library error"); + } + + PluginObjectsPtr libraryObjects = PluginObjectsPtr(new PluginObjects()); + const js_entity_definition_t *rawEntityListIterator = rawEntityList; + + LogDebug("#####"); + LogDebug("##### Plugin: " << libName << " is using deprecated API"); + LogDebug("#####"); + + while (rawEntityListIterator->parent_name != NULL && + rawEntityListIterator->object_name != NULL) + { + LogDebug("##### [" << rawEntityListIterator->object_name << "]: "); + LogDebug("##### Parent: " << rawEntityListIterator->parent_name); + LogDebug("#####"); + + libraryObjects->addObjects(rawEntityListIterator->parent_name, + rawEntityListIterator->object_name); + + ++rawEntityListIterator; + } + + // Unload library + if (dlclose(dlHandle) != 0) { + LogError("Cannot close plugin handle"); + } else { + LogDebug("Library is unloaded"); + } + + // Load export table + LogDebug("Library successfuly loaded and parsed"); + + return libraryObjects; +} + +PluginsInstaller::ReturnStatus PluginsInstaller::installPluginFromMetafile( + const std::string& path, const std::string& metaFilePath) +{ + if (!m_initialized) { + LogError("Plugins installer not initialized."); + return ReturnStatus::NotInitialized; + } + OptionalPluginMetafileData pluginData; + Try + { + pluginData = parseMetafile(metaFilePath); + } + Catch(PluginInstall::Exceptions::XMLFileParsingException) + { + LogError("Parsing metafile failed."); + return ReturnStatus::MetafileError; + } + if (!pluginData) { + return ReturnStatus::MetafileError; + } + + if (WrtDB::PluginDAO::isPluginInstalled(pluginData->m_libraryName)) { + LogDebug("Plugin already installed."); + return ReturnStatus::AlreadyInstalled; + } + Try { + LogError( + "path is: " << path << ", libraryName: " << + pluginData->m_libraryName); + PluginObjectsPtr objects = loadLibraryFromMetafile( + path + DIRECTORY_SEPARATOR + pluginData->m_libraryName); + + PluginHandle pluginHandle = + PluginDAO::registerPlugin(*pluginData, path); + + LogDebug("Plugin registered. Registering features..."); + + FOREACH(it, pluginData->m_featureContainer) + { + LogError("PluginHandle: " << pluginHandle); + FeatureDAO::RegisterFeature(*it, pluginHandle); + } + + LogDebug("Features registered. Registering objects..."); + + registerPluginObjects(pluginHandle, objects); + + LogDebug("Objects registered. Finishing..."); + + if (!registerAndUpdateInstallation(pluginHandle, objects)) { + return ReturnStatus::InstallationWaiting; + } + } Catch(DPL::Exception) { + LogError("Failed to make database entry."); + return ReturnStatus::DatabaseError; + } + + LogDebug("Plugin installed successfully."); + return ReturnStatus::Success; +} + +int PluginsInstaller::installAllPlugins() +{ + if (!m_initialized) { + LogError("Plugins installer not initialized."); + return INSTALLATION_ERROR; + } + LogDebug("Installing plugins ..."); + + std::string PLUGIN_PATH = std::string(GlobalConfig::GetDevicePluginPath()); + + DIR *dir; + dir = opendir(PLUGIN_PATH.c_str()); + + if (!dir) { + return INSTALLATION_ERROR; + } + + LogDebug("Plugin DIRECTORY IS" << PLUGIN_PATH); + int return_code; + struct dirent libdir; + struct dirent* result; + + errno = 0; + + std::list pluginsPaths; + + for (return_code = readdir_r(dir, &libdir, &result); + result != NULL && return_code == 0; + return_code = readdir_r(dir, &libdir, &result)) { + if (strcmp(libdir.d_name, ".") == 0 || + strcmp(libdir.d_name, "..") == 0) + { + continue; + } + + std::string path = PLUGIN_PATH; + path += "/"; + path += libdir.d_name; + + struct stat tmp; + + if (stat(path.c_str(), &tmp) == -1) { + LogError("Failed to open file" << path); + continue; + } + + if (!S_ISDIR(tmp.st_mode)) { + LogError("Not a directory" << path); + continue; + } + + LogDebug("Found plugin at " << path); + pluginsPaths.push_back(path); + } + + if (0 != return_code) + LogError("Error while reading directory."); + + if (-1 == closedir(dir)) { + LogError("Failed to close dir: " << PLUGIN_PATH); + } + + LogDebug("Plugins to install: " << pluginsPaths.size()); + + for (size_t k = 0; k <= pluginsPaths.size(); ++k) { + printf(" "); + } + printf("]\r["); + int installedPluginsCount = 0; + ReturnStatus ret = ReturnStatus::Unknown; + FOREACH(it, pluginsPaths) { + LogDebug("Preparing to plugin installation: " << *it); + ret = installPlugin(*it); + if (ReturnStatus::Success == ret) { + ++installedPluginsCount; + LogDebug("Plugin " << *it << " installed."); + } else if (ReturnStatus::InstallationWaiting == ret) { + LogWarning("Plugin not installed. Waiting for dependency"); + } else { + LogError("Plugin installation failed"); + } + printf("#"); + fflush(stdout); + } + printf("\n"); + installedPluginsCount += installWaitingPlugins(); + m_registry.UnloadAll(); + LogDebug("Installed " << installedPluginsCount + << " plugins of total: " << pluginsPaths.size()); + return installedPluginsCount; +} + +int PluginsInstaller::installWaitingPlugins() +{ + PluginHandleSetPtr waitingPlugins; + + waitingPlugins = + PluginDAO::getPluginHandleByStatus(PluginDAO::INSTALLATION_WAITING); + + int pluginsInstalled = 0; + FOREACH(it, *waitingPlugins) + { + if (resolvePluginDependencies(*it)) { + ++pluginsInstalled; + } + } + return pluginsInstalled; +} + +bool PluginsInstaller::resolvePluginDependencies(PluginHandle handle) +{ + PluginHandleSetPtr dependencies(new PluginHandleSet); + + PluginObjects::ObjectsPtr requiredObjects = + PluginDAO::getRequiredObjectsForPluginHandle(handle); + + PluginHandle depHandle = INVALID_PLUGIN_HANDLE; + + FOREACH(requiredObject, *requiredObjects) + { + depHandle = + PluginDAO::getPluginHandleForImplementedObject(*requiredObject); + + if (INVALID_PLUGIN_HANDLE == depHandle) { + LogError("Library implementing: " << + *requiredObject << " NOT FOUND"); + return false; + } + dependencies->insert(depHandle); + } + + PluginDAO::registerPluginLibrariesDependencies(handle, dependencies); + PluginDAO::setPluginInstallationStatus(handle, + PluginDAO::INSTALLATION_COMPLETED); + + return true; +} + +void PluginsInstaller::registerObjects(const PluginObjectsPtr& libObj, + const IObjectsListPtr& objects) const +{ + LogDebug("registerObjects invoked"); + + FOREACH(o, *objects) + { + auto children = CAST(*o)->GetChildren(); + + if (children) { + FOREACH(c, *children) + { + libObj->addObjects(CAST(*o)->GetName(), CAST(*c)->GetName()); + + LogDebug("[Parent << Object] " << CAST(*c)->GetName() + << " << " + << CAST(*o)->GetName()); + } + + registerObjects(libObj, children); + } + } +} + +PluginsInstaller::OptionalPluginMetafileData PluginsInstaller::parseMetafile( + const std::string& path) const +{ + LogDebug("Plugin Config file::" << path); + Try + { + PluginMetafileData pluginInfo; + PluginMetafileReader reader; + reader.initialize(path); + reader.read(pluginInfo); + + FOREACH(it, pluginInfo.m_featureContainer) { + LogDebug("Parsed feature : " << it->m_name); + + FOREACH(devCap, it->m_deviceCapabilities) { + LogDebug(" | DevCap : " << *devCap); + } + } + return OptionalPluginMetafileData(pluginInfo); + } + Catch(ValidationCore::ParserSchemaException::Base) { + LogError("Error during file processing " << path); + ThrowMsg(PluginInstall::Exceptions::XMLFileParsingException, + "Parsing metafile failed"); + } +} + +std::string PluginsInstaller::getLibraryName(const std::string& dirPath) const +{ + std::string pluginPath = dirPath; + size_t indexpos = pluginPath.find_last_of('/'); + + if (std::string::npos == indexpos) { + indexpos = 0; + } else { + indexpos += 1; // move after '/' + } + + std::string libName = pluginPath.substr(indexpos); + libName = WrtDB::GlobalConfig::GetPluginPrefix() + libName + + WrtDB::GlobalConfig::GetPluginSuffix(); + LogDebug("Plugin .so: " << libName); + return libName; +} + +bool PluginsInstaller::registerAndUpdateInstallation( + const WrtDB::DbPluginHandle& pluginHandle, + const PluginObjectsPtr& libraries) +{ + PluginHandleSetPtr handles = PluginHandleSetPtr(new PluginHandleSet); + + DbPluginHandle handle = INVALID_PLUGIN_HANDLE; + + //register requiredObjects + FOREACH(it, *(libraries->getDependentObjects())) + { + if (libraries->hasObject(*it)) { + LogDebug("Dependency from the same library. ignored"); + continue; + } + + handle = PluginDAO::getPluginHandleForImplementedObject(*it); + if (handle == INVALID_PLUGIN_HANDLE) { + LogError("Library implementing: " << *it << " NOT FOUND"); + PluginDAO::setPluginInstallationStatus( + pluginHandle, + PluginDAO::INSTALLATION_WAITING); + return false; + } + + handles->insert(handle); + } + + PluginDAO::registerPluginLibrariesDependencies(pluginHandle, handles); + + PluginDAO::setPluginInstallationStatus(pluginHandle, + PluginDAO::INSTALLATION_COMPLETED); + return true; +} + +bool PluginsInstaller::fillMappingInterfaces(PluginMetafileData& pluginData, + const std::string& filename) +{ + void *dlHandle = dlopen(filename.c_str(), RTLD_NOW); + if (dlHandle == NULL) { + const char* error = (const char*)dlerror(); + LogError( + "Failed to load plugin: " << filename << ". Reason: " << (error != NULL ? error : "unknown")); + return false; + } + Try + { + ExportedApi* entryPoint = + static_cast(dlsym(dlHandle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + LogError("Error: " << (error != NULL ? error : "unknown")); + ThrowMsg(PluginInstall::Exceptions::LibraryException, + "Library error"); + } + + // obtain feature -> dev-cap mapping + feature_mapping_interface_t mappingInterface = { NULL, NULL, NULL }; + entryPoint->GetProvidedFeatures(&mappingInterface); + + if (!mappingInterface.featGetter || !mappingInterface.release || + !mappingInterface.dcGetter) + { + LogError("Failed to obtain mapping interface from .so"); + ThrowMsg(PluginInstall::Exceptions::LibraryException, + "Library error"); + } + + feature_mapping_t* devcapMapping = mappingInterface.featGetter(); + + LogDebug("Getting mapping from features to device capabilities"); + + for (size_t i = 0; i < devcapMapping->featuresCount; ++i) { + PluginMetafileData::Feature feature; + feature.m_name = devcapMapping->features[i].feature_name; + + LogDebug("Feature: " << feature.m_name); + + const devcaps_t* dc = + mappingInterface.dcGetter( + devcapMapping, + devcapMapping->features[i]. + feature_name); + + LogDebug("device=cap: " << dc); + + if (dc) { + LogDebug("devcaps count: " << dc->devCapsCount); + + for (size_t j = 0; j < dc->devCapsCount; ++j) { + LogDebug("devcap: " << dc->deviceCaps[j]); + feature.m_deviceCapabilities.insert(dc->deviceCaps[j]); + } + } + + pluginData.m_featureContainer.insert(feature); + } + + mappingInterface.release(devcapMapping); + } Catch(PluginInstall::Exceptions::PluginsInstallerException) + { + LogError("Exception while feature mapping"); + dlclose(dlHandle); + return false; + } + + // Unload library + if (dlclose(dlHandle) != 0) { + LogError("Cannot close plugin handle"); + } else { + LogDebug("Library is unloaded"); + } + return true; +} + +void PluginsInstaller::registerPluginObjects( + const WrtDB::DbPluginHandle& handle, + const PluginObjectsPtr libObjects) +const +{ + //register implemented objects + PluginObjects::ObjectsPtr objects = + libObjects->getImplementedObject(); + + FOREACH(it, *objects) + { + WrtDB::PluginDAO::registerPluginImplementedObject(*it, handle); + } + + //register requiredObjects + objects = libObjects->getDependentObjects(); + + FOREACH(it, *objects) + { + if (libObjects->hasObject(*it)) { + LogDebug("Dependency from the same library. ignored"); + continue; + } + WrtDB::PluginDAO::registerPluginRequiredObject(*it, handle); + } +} + diff --git a/src_wearable/plugins-installer/plugin_installer.h b/src_wearable/plugins-installer/plugin_installer.h new file mode 100644 index 0000000..be0075c --- /dev/null +++ b/src_wearable/plugins-installer/plugin_installer.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer.h + * @author Andrzej Surdej(a.surdej@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H + +#include +#include +#include +#include +#include +#include + +#include + +class PluginsInstaller +{ + public: + static const int INSTALLATION_ERROR; + enum class ReturnStatus + { + Success, ///< Success + + NotInitialized, ///< Singleton not initialized + WrongPluginPath, ///< ? + MetafileError, ///< ? + AlreadyInstalled, ///< ? + LoadingLibraryError, ///< Loading library by dlopen failed. + /// It may be caused by missing symbols + InstallationWaiting, /// Installation failed due to dependencies + DatabaseError, /// Unable to update database + Unknown ///< Temporary error. Try to not use this. + }; + + bool initialize(); + int installAllPlugins(); + void deinitialize(); + + ReturnStatus installPlugin(const std::string& libPath); + ReturnStatus installPluginFromMetafile(const std::string& libPath, + const std::string& metaFilePath); + + int installWaitingPlugins(); + bool resolvePluginDependencies(PluginHandle handle); + + bool isInitialized(); + + private: + friend class DPL::Singleton; + + PluginsInstaller(); + virtual ~PluginsInstaller(); + + void registerObjects(const PluginObjectsPtr& libObj, + const WrtPluginsApi::IObjectsListPtr& objects) const; + + typedef boost::optional OptionalPluginMetafileData; + OptionalPluginMetafileData parseMetafile(const std::string& path) const; + + std::string getLibraryName(const std::string& dirPath) const; + bool registerAndUpdateInstallation(const PluginHandle& pluginHandle, + const PluginObjectsPtr& libraries); + bool fillMappingInterfaces(WrtDB::PluginMetafileData& pluginData, + const std::string& filename); + void registerPluginObjects(const PluginHandle& handle, + const PluginObjectsPtr libObjects) const; + void checkDatabaseTablesExistance(); + PluginObjectsPtr loadLibraryFromMetafile(const std::string& libName) const; + + WrtPluginsApi::PluginRegistry m_registry; + bool m_initialized; + bool m_reinstall; +}; + +typedef DPL::Singleton PluginsInstallerSingleton; + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H */ + diff --git a/src_wearable/plugins-installer/plugin_installer_errors.h b/src_wearable/plugins-installer/plugin_installer_errors.h new file mode 100644 index 0000000..9a94a79 --- /dev/null +++ b/src_wearable/plugins-installer/plugin_installer_errors.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer_errors.h + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H + +#include + +namespace PluginInstall { +namespace Exceptions { +DECLARE_EXCEPTION_TYPE(DPL::Exception, PluginsInstallerException) +DECLARE_EXCEPTION_TYPE(PluginsInstallerException, LibraryException) +DECLARE_EXCEPTION_TYPE(PluginsInstallerException, XMLFileParsingException) +} //namespace +} //namespace + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H */ + diff --git a/src_wearable/plugins-installer/plugin_installer_types.h b/src_wearable/plugins-installer/plugin_installer_types.h new file mode 100644 index 0000000..ae3a5db --- /dev/null +++ b/src_wearable/plugins-installer/plugin_installer_types.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_installer_types.h + * @author Andrzej Surdej (a.surdej@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H + +#include + +/* Define db type */ +typedef WrtDB::DbWidgetHandle WidgetHandle; +typedef WrtDB::DbWidgetHandleList WidgetHandleList; + +typedef WrtDB::DbWidgetFeature WidgetFeature; +typedef WrtDB::DbWidgetFeatureSet WidgetFeatureSet; + +typedef WrtDB::DbPluginHandle PluginHandle; + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H */ diff --git a/src_wearable/plugins-installer/plugin_metafile_reader.cpp b/src_wearable/plugins-installer/plugin_metafile_reader.cpp new file mode 100644 index 0000000..b65c2e3 --- /dev/null +++ b/src_wearable/plugins-installer/plugin_metafile_reader.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_metafile_reader.cpp + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#include "plugin_metafile_reader.h" + +using namespace WrtDB; + +namespace { +const std::string XML_NAMESPACE = ""; + +const std::string TOKEN_LIBRARY_NAME = "library-name"; +const std::string TOKEN_API_FEATURE = "api-feature"; +const std::string TOKEN_NAME = "name"; +const std::string TOKEN_DEVICECAPABILITY = "device-capability"; +} + +PluginMetafileReader::PluginMetafileReader() : m_parserSchema(this) +{ + m_parserSchema.addEndTagCallback( + TOKEN_LIBRARY_NAME, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndLibraryName); + + m_parserSchema.addEndTagCallback( + TOKEN_API_FEATURE, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndApiFeature); + + m_parserSchema.addEndTagCallback( + TOKEN_NAME, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndName); + + m_parserSchema.addEndTagCallback( + TOKEN_DEVICECAPABILITY, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndDeviceCapability); +} + +void PluginMetafileReader::blankFunction(PluginMetafileData & /* data */) +{} + +void PluginMetafileReader::tokenEndLibraryName(PluginMetafileData &data) +{ + data.m_libraryName = m_parserSchema.getText(); +} + +void PluginMetafileReader::tokenEndApiFeature(PluginMetafileData &data) +{ + data.m_featureContainer.insert(m_feature); + m_feature.m_deviceCapabilities.clear(); +} + +void PluginMetafileReader::tokenEndName(PluginMetafileData & /* data */) +{ + m_feature.m_name = m_parserSchema.getText(); +} + +void PluginMetafileReader::tokenEndDeviceCapability(PluginMetafileData& /*data*/) +{ + m_feature.m_deviceCapabilities.insert(m_parserSchema.getText()); +} + diff --git a/src_wearable/plugins-installer/plugin_metafile_reader.h b/src_wearable/plugins-installer/plugin_metafile_reader.h new file mode 100644 index 0000000..b0c88f0 --- /dev/null +++ b/src_wearable/plugins-installer/plugin_metafile_reader.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_metafile_reader.h + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_METAFILE_READER_H_ +#define WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_METAFILE_READER_H_ + +#include +#include + +class PluginMetafileReader +{ + public: + PluginMetafileReader(); + + void initialize(const std::string &filename) + { + m_parserSchema.initialize(filename, + true, + ValidationCore::SaxReader::VALIDATION_DTD, + std::string()); + } + + void read(WrtDB::PluginMetafileData &data) + { + m_parserSchema.read(data); + } + + private: + void blankFunction(WrtDB::PluginMetafileData &data); + + void tokenEndLibraryName(WrtDB::PluginMetafileData &data); + void tokenEndApiFeature(WrtDB::PluginMetafileData &data); + void tokenEndName(WrtDB::PluginMetafileData &data); + void tokenEndDeviceCapability(WrtDB::PluginMetafileData &data); + + WrtDB::PluginMetafileData::Feature m_feature; + + ValidationCore::ParserSchema m_parserSchema; +}; + +#endif diff --git a/src_wearable/plugins-installer/plugin_objects.cpp b/src_wearable/plugins-installer/plugin_objects.cpp new file mode 100644 index 0000000..ae65b0f --- /dev/null +++ b/src_wearable/plugins-installer/plugin_objects.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_objects.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include +#include +#include "plugin_objects.h" +#include + +namespace { +const char* SEPARATOR = "."; +const std::string GLOBAL_OBJECT_NAME = WrtPluginsApi::IObject::WINDOW_OBJECT(); +const std::string OLD_GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; + +std::string normalizeName(const std::string& objectName) +{ + if (objectName.empty()) { + LogError("Normalize name, name size is 0"); + return objectName; + } + + if (!objectName.compare(0, GLOBAL_OBJECT_NAME.size(), + GLOBAL_OBJECT_NAME)) + { + return objectName; + } + if (!objectName.compare(0, OLD_GLOBAL_OBJECT_NAME.size(), + OLD_GLOBAL_OBJECT_NAME)) + { + return GLOBAL_OBJECT_NAME; + } + + //each object in storage has name started from $GLOBAL_OBJECT_NAME$ + return GLOBAL_OBJECT_NAME + std::string(SEPARATOR) + objectName; +} + +std::string normalizeName(const std::string& objectName, + const std::string& parentName) +{ + if (objectName.empty() || parentName.empty()) { + LogError("Normalize name, name size or parent name size is 0"); + return std::string(); + } + + std::string normalizedName; + normalizedName = normalizeName(parentName) + + std::string(SEPARATOR) + objectName; + + return normalizedName; +} +} + +PluginObjects::PluginObjects() +{ + m_implemented = ObjectsPtr(new Objects()); + m_dependent = ObjectsPtr(new Objects()); +} + +PluginObjects::ObjectsPtr PluginObjects::getImplementedObject() const +{ + return m_implemented; +} + +PluginObjects::ObjectsPtr PluginObjects::getDependentObjects() const +{ + return m_dependent; +} + +void PluginObjects::addObjects(const std::string& parentName, + const std::string& name) +{ + LogDebug("\n Parent: " << parentName + << "\n Name: " << name + << "\n After: Implemented: " << + normalizeName(name, parentName) + << "\n After Dependent: " << + normalizeName(parentName) + ); + + addImplementedObject(normalizeName(name, parentName)); + addDependentObject(normalizeName(parentName)); +} + +void PluginObjects::addDependentObject(const std::string& value) +{ + if (!value.compare(GLOBAL_OBJECT_NAME)) { + //dont add dependency to GLOBAL_OBJECT + return; + } + m_dependent->insert(value); +} + +bool PluginObjects::hasObject(const std::string& name) const +{ + return m_implemented->find(name) != m_implemented->end(); +} + +void PluginObjects::addImplementedObject(const std::string& value) +{ + m_implemented->insert(value); +} diff --git a/src_wearable/plugins-installer/plugin_objects.h b/src_wearable/plugins-installer/plugin_objects.h new file mode 100644 index 0000000..eda28a3 --- /dev/null +++ b/src_wearable/plugins-installer/plugin_objects.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin_objects.h + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_OBJECTS_H_ +#define WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_OBJECTS_H_ + +#include +#include +#include +#include + +#include +//TODO TO BE MOVED SOMEWHERE ELSE +// AS OTHER MODULES (LIKE DAO) USE IT + +class PluginObjects : public WrtDB::PluginObjectsDAO +{ + public: + explicit PluginObjects(); + + //getters for objects from library + ObjectsPtr getImplementedObject() const; + ObjectsPtr getDependentObjects() const; + + //add object declaration + void addObjects(const std::string& parentName, + const std::string& name); + + //check if library implemements object given as name + bool hasObject(const std::string& name) const; + + private: + void addImplementedObject(const std::string& value); + void addDependentObject(const std::string& value); +}; + +typedef DPL::SharedPtr PluginObjectsPtr; + +#endif diff --git a/src_wearable/plugins-installer/plugin_utils.cpp b/src_wearable/plugins-installer/plugin_utils.cpp new file mode 100644 index 0000000..42cc49d --- /dev/null +++ b/src_wearable/plugins-installer/plugin_utils.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin-utils.cpp + * @author + * @version 1.0 + * @brief Header file for plugin util + */ + +#include "plugin_utils.h" +#include +#include +#include +#include + +using namespace WrtDB; + +namespace PluginUtils { +//checks if file exists and is regular file +bool checkFileExistance(const std::string& filename) +{ + struct stat tmp; + + if (0 == stat(filename.c_str(), &tmp) && S_ISREG(tmp.st_mode)) { + return true; + } + return false; +} + +std::string cutOffFileName(const std::string& path) +{ + size_t found = path.find_last_of("/"); + if (found == std::string::npos) { + return path; + } else { + return path.substr(0, found); + } +} + +bool checkPath(const std::string& path) +{ + struct stat st; + if (0 == stat(path.c_str(), &st) && S_ISDIR(st.st_mode)) { + return true; + } + LogError("Cannot access directory [ " << path << " ]"); + return false; +} + +bool checkPaths() +{ + bool if_ok = true; + if_ok &= (checkPath(cutOffFileName( + GlobalConfig::GetWrtDatabaseFilePath()))); + if (!if_ok) { + LogError( + "Path <" << GlobalConfig::GetWrtDatabaseFilePath() << + "> does not exist."); + } + + if_ok &= (checkPath(GlobalConfig::GetDevicePluginPath())); + if (!if_ok) { + LogError( + "Path <" << GlobalConfig::GetDevicePluginPath() << + "> does not exist."); + } + + if_ok &= (checkPath(GlobalConfig::GetUserInstalledWidgetPath())); + if (!if_ok) { + LogError( + "Path <" << GlobalConfig::GetUserInstalledWidgetPath() << + "> does not exist."); + } + return if_ok; +} +} //namespace PluginUtils diff --git a/src_wearable/plugins-installer/plugin_utils.h b/src_wearable/plugins-installer/plugin_utils.h new file mode 100644 index 0000000..a542e28 --- /dev/null +++ b/src_wearable/plugins-installer/plugin_utils.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file plugin-utils.h + * @author + * @version 1.0 + * @brief Header file for plugin util + */ +#ifndef PLUGIN_UTILS_H +#define PLUGIN_UTILS_H + +#include +#include + +namespace PluginUtils { +bool checkFileExistance(const std::string& filename); + +std::string cutOffFileName(const std::string& path); +bool checkPath(const std::string& path); +bool checkPaths(); +} +#endif // PLUGIN_UTILS_H diff --git a/src_wearable/plugins-installer/wrt_plugins_installer.cpp b/src_wearable/plugins-installer/wrt_plugins_installer.cpp new file mode 100644 index 0000000..c664350 --- /dev/null +++ b/src_wearable/plugins-installer/wrt_plugins_installer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* @file wrt_plugins_installer.cpp + * @author Andrzej Surdej(a.surdej@gmail.com) + * @version 1.0 + * @brief Main file for plugins installer + */ + +#include +#include +#include +#include +#include + +int main(int /*argc*/, char */*argv*/[]) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + DPL::Log::LogSystemSingleton::Instance().SetTag("PLUGINS_INSTALLER"); + LogDebug("Plugins installation started."); + + printf("Installing plugins...\n"); + PluginsInstallerSingleton::Instance().initialize(); + int installed = + PluginsInstallerSingleton::Instance().installAllPlugins(); + PluginsInstallerSingleton::Instance().deinitialize(); + printf("Completed: %d plugins installed.\n", installed); + + LogDebug("All plugins installed successfuly"); + return 0; + } + UNHANDLED_EXCEPTION_HANDLER_END +} diff --git a/src_wearable/plugins-ipc-message/CMakeLists.txt b/src_wearable/plugins-ipc-message/CMakeLists.txt new file mode 100644 index 0000000..d3da03e --- /dev/null +++ b/src_wearable/plugins-ipc-message/CMakeLists.txt @@ -0,0 +1,60 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# @file CMakeLists.txt +# @author Jihoon Chung (jihoon.chung@samsung.com) +# @version 1.0 +# + +pkg_search_module(dpl REQUIRED dpl-efl) +pkg_search_module(webkit2 REQUIRED ewebkit2) + +set(PLUGINS_IPC_MESSAGE_SOURCES + ${PLUGINS_IPC_MESSAGE_DIRS}/ipc_message_support.cpp +) + +INCLUDE_DIRECTORIES( + ${PLUGINS_IPC_MESSAGE_DIRS} + ${webkit2_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGINS_IPC_MESSAGE_LIB} SHARED + ${PLUGINS_IPC_MESSAGE_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_PLUGINS_IPC_MESSAGE_LIB} + ${dpl_LIBRARIES} + ${webkit2_LIBRARIES} +) + +INSTALL(TARGETS ${TARGET_PLUGINS_IPC_MESSAGE_LIB} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES + ipc_message_support.h + DESTINATION include/plugins-ipc-message) diff --git a/src_wearable/plugins-ipc-message/ipc_message_support.cpp b/src_wearable/plugins-ipc-message/ipc_message_support.cpp new file mode 100644 index 0000000..b892289 --- /dev/null +++ b/src_wearable/plugins-ipc-message/ipc_message_support.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file ipc_message_support.cpp + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation of IPC between plugins and UI Process + */ +#include "ipc_message_support.h" + +#include +#include +#include +#include +#include +#include +#include + +static WKBundleRef s_injectedBundleRef = NULL; +static unsigned int s_xWindowHandle = 0; + +namespace { +const char* const TIZEN_GET_WINDOW_HANDLE = "tizen://getWindowHandle"; +const char* const TIZEN_CLEAR_ALL_COOKIES = "tizen://clearAllCookies"; + +static void sendPostMessage(const char* name, const char* body) +{ + WKStringRef nameWKString = WKStringCreateWithUTF8CString(name); + WKStringRef bodyWKString = NULL; + if (body) { + bodyWKString = WKStringCreateWithUTF8CString(body); + } + + WKBundlePostMessage(s_injectedBundleRef, + nameWKString, + bodyWKString); + WKRelease(nameWKString); + if (bodyWKString) { + WKRelease(bodyWKString); + } +} + +static int sendAsyncMessage(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data) +{ + using namespace IPCMessageSupport; + + int handle = AsyncConnectionManager::instance().addConnection(AsyncConnectionPtr(new AsyncConnection(replyCallback, data))); + + std::string strBody = body; + std::stringstream ss; + + ss << handle; + strBody = ss.str() + "_" + strBody; + + sendPostMessage(name, strBody.c_str()); + + return handle; +} + +} // namespace + + +namespace IPCMessageSupport { + +AsyncConnectionManager::~AsyncConnectionManager() +{ + m_connectionMap.clear(); +} + +AsyncConnectionManager &AsyncConnectionManager::instance() +{ + static AsyncConnectionManager instance; + + return instance; +} + +int AsyncConnectionManager::addConnection(AsyncConnectionPtr connection) +{ + static int latestHandle = -1; + int newHandle; + + latestHandle++; + if (latestHandle < 0) latestHandle = 0; + + newHandle = latestHandle; + + m_connectionMap.insert(AsyncConnectionMap::value_type(newHandle, connection)); + + return newHandle; +} + +bool AsyncConnectionManager::removeConnection(int handle) +{ + bool ret = (m_connectionMap.erase(handle) == 1); + + return ret; +} + +AsyncConnectionPtr AsyncConnectionManager::getConnection(int handle) +{ + AsyncConnectionMap::iterator iter = m_connectionMap.find(handle); + + if (iter != m_connectionMap.end()) + { + return iter->second; + } + + return AsyncConnectionPtr(); +} + + +} // namespace IPCMessageSupport + + +void IPCMessageSupport::setWKBundleRef(WKBundleRef bundleRef) +{ + _D("called"); + s_injectedBundleRef = bundleRef; +} + +void IPCMessageSupport::setXwindowHandle(unsigned int handle) +{ + _D("called"); + s_xWindowHandle = handle; +} + +const char* IPCMessageSupport::sendMessageToUiProcess( + const char* name, + const char* body) +{ + _D("called"); + if (s_injectedBundleRef == NULL) { + _E("UI Process information isn't set"); + return NULL; + } + _D("name = [%s]", name); + if (body) { + _D("body = [%s]", body); + } + + if (!name) { + return NULL; + } + + // tizen://getWindowHandle + if (!strcmp(name, TIZEN_GET_WINDOW_HANDLE)) { + if (s_xWindowHandle == 0) { + return NULL; + } else { + std::stringstream ss; + ss << s_xWindowHandle; + std::string ret = ss.str(); + return strdup(ret.c_str()); + } + } + + // tizen://clearAllCookies + if (!strcmp(name, TIZEN_CLEAR_ALL_COOKIES)) { + sendPostMessage(name, body); + return NULL; + } + + return NULL; +} + +int IPCMessageSupport::sendAsyncMessageToUiProcess(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data) +{ + _D("called"); + + if (s_injectedBundleRef == NULL) + { + _E("UI Process information isn't set"); + return -1; + } + + if (name == NULL) + { + _E("msg name is null!"); + return -1; + } + + if (body == NULL) + { + body = ""; + } + + _D("name = [%s]", name); + if (!body) { + _D("body = [%s]", body); + } + + return sendAsyncMessage(name, body, replyCallback, data); +} + +void* IPCMessageSupport::ignoreAsyncMessageReply(int handle) +{ + _D("called"); + + AsyncConnectionPtr connection = AsyncConnectionManager::instance().getConnection(handle); + + if (!connection) + { + return NULL; + } + + AsyncConnectionManager::instance().removeConnection(handle); + + return connection->data; +} + +void IPCMessageSupport::replyAsyncMessageToWebProcess(Ewk_Context* ewkContext, int handle, const char* body) +{ + _D("called"); + + if (ewkContext == NULL) + { + return; + } + + std::string strBody = (body) ? (body) : ""; + std::stringstream ss; + ss << handle; + + strBody = ss.str() + "_" + strBody; + + ewk_context_message_post_to_injected_bundle(ewkContext, REPLY_ASYNC, strBody.c_str()); +} diff --git a/src_wearable/plugins-ipc-message/ipc_message_support.h b/src_wearable/plugins-ipc-message/ipc_message_support.h new file mode 100644 index 0000000..b5463e9 --- /dev/null +++ b/src_wearable/plugins-ipc-message/ipc_message_support.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. + */ +/** + * @file ipc_message_support.h + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation of IPC between plugins and UI Process + */ +#ifndef WRT_SRC_IPC_MESSAGE_SUPPORT +#define WRT_SRC_IPC_MESSAGE_SUPPORT + +#include +#include +#include +#include +#include + +typedef void (*AsyncReplyCallback)(unsigned int, void*, const char*); + +namespace IPCMessageSupport { + +static const char * const REPLY_ASYNC = "ToInjectedBundle::REPLY_ASYNC"; +static const char * const TIZEN_CHANGE_USERAGENT = "tizen://changeUA"; +static const char * const TIZEN_DELETE_ALL_COOKIES = "tizen://deleteAllCookies"; +static const char * const TIZEN_EXIT = "tizen://exit"; +static const char * const TIZEN_HIDE = "tizen://hide"; + +class AsyncConnection +{ + public: + AsyncReplyCallback replyCallback; + void* data; + + AsyncConnection(AsyncReplyCallback r, void* d) : + replyCallback(r), + data(d) + { + } +}; + +typedef std::shared_ptr AsyncConnectionPtr; +typedef std::map AsyncConnectionMap; + +class AsyncConnectionManager +{ + private: + AsyncConnectionMap m_connectionMap; + + public: + ~AsyncConnectionManager(); + + // Singleton + static AsyncConnectionManager &instance(); + + int addConnection(AsyncConnectionPtr connection); + bool removeConnection(int handle); + AsyncConnectionPtr getConnection(int handle); + +}; + +void setWKBundleRef(WKBundleRef bundleRef); +void setXwindowHandle(unsigned int handle); +const char* sendMessageToUiProcess(const char* name, const char* body); +int sendAsyncMessageToUiProcess(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data); +void* ignoreAsyncMessageReply(int handle); +void replyAsyncMessageToWebProcess(Ewk_Context* ewkContext, int handle, const char* body); +} + +#endif // WRT_SRC_IPC_MESSAGE_SUPPORT diff --git a/src_wearable/standards/CMakeLists.txt b/src_wearable/standards/CMakeLists.txt new file mode 100644 index 0000000..83ff664 --- /dev/null +++ b/src_wearable/standards/CMakeLists.txt @@ -0,0 +1,16 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +add_subdirectory(W3C) diff --git a/src_wearable/standards/W3C/CMakeLists.txt b/src_wearable/standards/W3C/CMakeLists.txt new file mode 100644 index 0000000..11828fb --- /dev/null +++ b/src_wearable/standards/W3C/CMakeLists.txt @@ -0,0 +1,15 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +add_subdir(Widget) diff --git a/src_wearable/standards/W3C/DESCRIPTION b/src_wearable/standards/W3C/DESCRIPTION new file mode 100644 index 0000000..8e32c7b --- /dev/null +++ b/src_wearable/standards/W3C/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +W3C plugin - Widget Interface diff --git a/src_wearable/standards/W3C/Widget/CMakeLists.txt b/src_wearable/standards/W3C/Widget/CMakeLists.txt new file mode 100644 index 0000000..74bb6da --- /dev/null +++ b/src_wearable/standards/W3C/Widget/CMakeLists.txt @@ -0,0 +1,51 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +ADD_DEFINITIONS("-DWRT_PLUGINS_WIDGET_LOG") + +set(TARGET_NAME "wrt-plugins-w3c-widget-interface") + +pkg_search_module(webkit2 REQUIRED ewebkit2) +pkg_search_module(plugin-types REQUIRED wrt-plugins-types) + +set(SRCS + ${SRCS_COMMONS} + JSWidget.cpp + JSPreferences.cpp + plugin_initializer.cpp + plugin_config.cpp +) + +include_directories( + ${API_WIDGET_PATH} + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} + ${PLUGINS_API_SUPPORT_DIRS} +) + +add_library(${TARGET_NAME} SHARED ${SRCS}) +target_link_libraries(${TARGET_NAME} + ${LIBS_COMMON} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} + ${TARGET_JS_OVERLAY} + ${TARGET_PLUGINS_API_SUPPORT} + wrt-plugins-widget + wrt-plugins-localstorage + wrt-plugins-storageevent + wrt-dispatch-event +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION /usr/lib/wrt-plugins/w3c-widget-interface) diff --git a/src_wearable/standards/W3C/Widget/JSPreferences.cpp b/src_wearable/standards/W3C/Widget/JSPreferences.cpp new file mode 100644 index 0000000..3730f2c --- /dev/null +++ b/src_wearable/standards/W3C/Widget/JSPreferences.cpp @@ -0,0 +1,528 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSPreferences.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#include "JSPreferences.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// import temporarily from JSContextRefPrivate.h +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +using namespace std; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::LocalStorage::Api; +using namespace WrtDeviceApis::StorageEvent::Api; + +#define PREFERENCES_PLUGIN_NAME "preferences" +#define LOCAL_STORAGE_PROPERTY_LENGTH "length" + +#define CATCH_EXCEPTION_NO_MODIFABLE \ + Catch(Commons::LocalStorageValueNoModifableException) { \ + _E("The item is read only"); \ + return JSDOMExceptionFactory:: \ + NoModificationAllowedException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + _E("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + _E("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + _E("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + _E("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_OUT_OF_RANGE \ + Catch(Commons::OutOfRangeException) { \ + _E("OutOfRangeException"); \ + return JSDOMExceptionFactory:: \ + QuotaExceededException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_INVALID_ARG \ + Catch(Commons::InvalidArgumentException) { \ + _E("Pair for given key doesnt exist"); \ + return JSValueMakeNull(context); \ + } + +namespace WrtPlugins { +namespace W3C { +ILocalStoragePtr getIStorage(JSObjectRef arg) +{ + _D("get localstorage object"); + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + _E("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->istorage; +} + +JSObjectRef getWidgetObject(JSObjectRef arg) +{ + _D("get widget object"); + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + _E("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->widgetObject; +} + +enum class ModificationType +{ + RemoveItem, + SetItem +}; + +//this function may throw exceptions +IStorageEventPtr modifyItemAndCreateEvent(ModificationType type, + JSObjectRef thisObject, + const string& key, + const string& value = std::string()) +{ + DPL::OptionalStdString oldValue = + getIStorage(thisObject)->getValue(key); + + if (ModificationType::SetItem == type) { + getIStorage(thisObject)->setItem(key, value, false); + } else if (ModificationType::RemoveItem == type) { + getIStorage(thisObject)->removeItem(key); + } else { + Assert(!"Wrong Modification type"); + } + + DPL::OptionalStdString newValue = + getIStorage(thisObject)->getValue(key); + + //create event object + IStorageEventPtr storageEvent = getStorageEvent(); + + //key + storageEvent->setKey(key); + //oldvalue + if (!!oldValue) { + storageEvent->setOldValue(*oldValue); + } + //newValue + if (!!newValue) { + storageEvent->setNewValue(*newValue); + } + + return storageEvent; +} + +JSClassDefinition JSPreferences::m_classInfo = { + 0, + kJSClassAttributeNone, + PREFERENCES_PLUGIN_NAME, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticFunction JSPreferences::m_function[] = { + { "setItem", JSPreferences::setItem, kJSPropertyAttributeNone }, + { "removeItem", JSPreferences::removeItem, kJSPropertyAttributeNone }, + { "getItem", JSPreferences::getItem, kJSPropertyAttributeNone }, + { "clear", JSPreferences::clear, kJSPropertyAttributeNone }, + { "key", JSPreferences::key, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSPreferences::m_property[] = { + { LOCAL_STORAGE_PROPERTY_LENGTH, + JSPreferences::getLength, + NULL, + kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSPreferences::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSPreferences::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSPreferences::m_jsClassRef = + JSClassCreate(JSPreferences::getClassInfo()); + +void JSPreferences::initialize(JSContextRef context, + JSObjectRef object) +{ + _D("entered. Context: %p", context); + + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(object)); + + AssertMsg(priv, "private object of preferences is NULL"); +} + +void JSPreferences::finalize(JSObjectRef object) +{ + _D("entered"); + LocalStoragePrivateData* priv = + static_cast(JSObjectGetPrivate(object)); + + delete priv; +} + +JSValueRef JSPreferences::removeItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + Converter converter(context); + + std::string key = converter.toString(arguments[0]); + + DPL::OptionalStdString oldValue = getIStorage(thisObject)->getValue(key); + getIStorage(thisObject)->removeItem(key); + DPL::OptionalStdString newValue = getIStorage(thisObject)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValue, newValue, ""); + + return JSValueMakeNull(context); + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::setItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + Converter converter(context); + + std::string key = converter.toString(arguments[0]); + std::string value = converter.tryString(arguments[1]); + + DPL::OptionalStdString oldValue = getIStorage(thisObject)->getValue(key); + getIStorage(thisObject)->setItem(key, value, false); + DPL::OptionalStdString newValue = getIStorage(thisObject)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValue, newValue, ""); + + return JSValueMakeUndefined(context); + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_OUT_OF_RANGE +} + +JSValueRef JSPreferences::clear(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef /*arguments*/[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + getIStorage(thisObject)->clear(false); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + const auto& null = DPL::OptionalStdString(); + + DispatchEventSupport::dispatchStorageEvent(g_context, null, null, null, ""); + + return JSValueMakeNull(context); + } + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::getItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + Converter converter(context); + + std::string key = converter.tryString(arguments[0]); + + _D("Getting item for key %s", key.c_str()); + + DPL::OptionalStdString value = + getIStorage(thisObject)->getValue(key); + + if (!value) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(*value); + } + } + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::key(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + _D("entered"); + + Try { + if (argumentCount < 1) { + _E("No argument found"); + Throw(Commons::InvalidArgumentException); + } + + Converter converter(context); + + size_t n = converter.toSizeT(arguments[0]); + + std::string value = getIStorage(thisObject)->getKeyByIndex(n); + + return converter.toJSValueRef(value); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_INVALID_ARG +} + +JSValueRef JSPreferences::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + _D("enter"); + + Try + { + Converter converter(context); + + size_t value = getIStorage(object)->getStorageSize(); + return converter.toJSValueRef(value); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSPreferences::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + _D("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + if (!getIStorage(object)->getValue(key)) { + return false; + } else { + return true; + } + } + + Catch(Commons::InvalidArgumentException) { + _E("Pair for given key doesnt exist"); + } + + Catch(Commons::ConversionException) { + _E("Error on conversion"); + } + + Catch(Commons::NullPointerException) { + _E("Error on pointer, null value"); + } + + Catch(Commons::PlatformException){ + _E("PlatformException occured"); + } + return false; +} + +JSValueRef JSPreferences::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + _D("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + DPL::OptionalStdString value = + getIStorage(object)->getValue(key); + + if (!value) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(*value); + } + } + + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSPreferences::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef jvalue, + JSValueRef* exception) +{ + _D("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + std::string value = converter.toString(jvalue); + + DPL::OptionalStdString oldValue = getIStorage(object)->getValue(key); + getIStorage(object)->setItem(key, value, false); + DPL::OptionalStdString newValue = getIStorage(object)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + std::string oldValueStr = ""; + std::string newValueStr = ""; + + if (!!oldValue) { oldValueStr = *oldValue; } + if (!!newValue) { newValueStr = *newValue; } + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValueStr, newValueStr, ""); + + return true; + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_OUT_OF_RANGE + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + + return false; +} + +#undef CATCH_EXCEPTION_NO_MODIFABLE +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +#undef CATCH_EXCEPTION_OUT_OF_RANGE +#undef CATCH_EXCEPTION_INVALID_ARG +} +} diff --git a/src_wearable/standards/W3C/Widget/JSPreferences.h b/src_wearable/standards/W3C/Widget/JSPreferences.h new file mode 100644 index 0000000..b86bae8 --- /dev/null +++ b/src_wearable/standards/W3C/Widget/JSPreferences.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSPreferences.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_WIDGET_PREFERENCES_H_ +#define _WRT_PLUGIN_JS_WIDGET_PREFERENCES_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +struct LocalStoragePrivateData { + WrtDeviceApis::LocalStorage::Api::ILocalStoragePtr istorage; + //parent + JSObjectRef widgetObject; +}; + +class JSPreferences +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks + * that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function. + */ + static JSStaticFunction m_function[]; + + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + //Modified functions for Preference object + static JSValueRef removeItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef clear(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef key(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; +} +} + +#endif diff --git a/src_wearable/standards/W3C/Widget/JSWidget.cpp b/src_wearable/standards/W3C/Widget/JSWidget.cpp new file mode 100644 index 0000000..ec7b7b2 --- /dev/null +++ b/src_wearable/standards/W3C/Widget/JSWidget.cpp @@ -0,0 +1,561 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSWidget.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#include "JSWidget.h" +#include +#include +#include +#include +#include +#include +#include +#include "JSPreferences.h" +#include +#include +#include + +// temporary +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +#define CATCH_EXCEPTION_NO_MODIFABLE \ + Catch(Commons::LocalStorageValueNoModifableException) { \ + _E("The item is read only"); \ + return JSDOMExceptionFactory:: \ + NoModificationAllowedException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + _E("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + _E("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + _E("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + _E("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_OUT_OF_RANGE \ + Catch(Commons::OutOfRangeException) { \ + _E("OutOfRangeException"); \ + return JSDOMExceptionFactory:: \ + QuotaExceededException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_INVALID_ARG \ + Catch(Commons::InvalidArgumentException) { \ + _E("Pair for given key doesnt exist"); \ + return JSValueMakeNull(context); \ + } + +#define WIDGET_PLUGIN_NAME "Widget" + +#define WRT_WIDGET_PROPERTY_AUTHOR "author" +#define WRT_WIDGET_PROPERTY_AUTHOR_EMAIL "authorEmail" +#define WRT_WIDGET_PROPERTY_AUTHOR_HREF "authorHref" +#define WRT_WIDGET_PROPERTY_DESCRIPTION "description" +#define WRT_WIDGET_PROPERTY_ID "id" +#define WRT_WIDGET_PROPERTY_NAME "name" +#define WRT_WIDGET_PROPERTY_SHORT_NAME "shortName" +#define WRT_WIDGET_PROPERTY_VERSION "version" +#define WRT_WIDGET_PROPERTY_HEIGHT "height" +#define WRT_WIDGET_PROPERTY_WIDTH "width" + +namespace WrtPlugins { +namespace W3C { +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Widget; + +struct WidgetPrivateObject +{ + Widget::Api::IWidgetPtr iwidget; + JSObjectRef preferencesObject; + //TEMP + //int widgetId // TODO: check is it necessary (g.rynkowski) + JSObjectRef widgetObject; +}; +typedef std::shared_ptr WidgetPrivateObjectPtr; + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT +::Type JSWidgetPrivateObject; + +WrtDeviceApis::Widget::Api::IWidgetPtr getIWidget(JSObjectRef arg) +{ + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject()->iwidget; +} + +LocalStorage::Api::ILocalStoragePtr getLocalStorage(int widgetId) +{ + LocalStorage::Api::ILocalStoragePtr storage( + LocalStorage::Api::getLocalStorage(widgetId)); + + return storage; +} + +JSObjectRef getPreferences(JSObjectRef arg) +{ + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(arg)); + + if (!priv) { + LogError("Private object not initialized"); + return NULL; + } + + return priv->getObject()->preferencesObject; +} + +JSObjectRef createPreferencesObject(JSContextRef context, + JSObjectRef widgetObject, + int widgetId) +{ + AssertMsg(widgetObject, "Widget Object can'n be null"); + //delete is invoked in JSPreferences::finalize + LocalStoragePrivateData* priv = new LocalStoragePrivateData; + AssertMsg(priv, "Private data is null"); + priv->istorage = getLocalStorage(widgetId); + priv->widgetObject = widgetObject; + + JSObjectRef preferences = JSObjectMake(context, + JSPreferences::getClassRef(), + priv); + + if (!preferences) { + LogError("Preferences object is null"); + delete priv; + } + //Unprotect is called in JSWidget::finalize + JSValueProtect(context, preferences); + + return preferences; +} + +JSClassDefinition JSWidget::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + callAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSWidget::m_property[] = { + { WRT_WIDGET_PROPERTY_AUTHOR, JSWidget::getAuthor, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_AUTHOR_EMAIL, JSWidget::getAuthorEmail, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_AUTHOR_HREF, JSWidget::getAuthorHref, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_DESCRIPTION, JSWidget::getDescription, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_ID, JSWidget::getId, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_NAME, JSWidget::getName, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_SHORT_NAME, JSWidget::getShortName, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_VERSION, JSWidget::getVersion, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_HEIGHT, JSWidget::getHeight, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_WIDTH, JSWidget::getWidth, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSWidget::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSWidget::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSWidget::m_jsClassRef = JSClassCreate(JSWidget::getClassInfo()); + +void JSWidget::initialize(JSContextRef context, + JSObjectRef object) +{ + JSGlobalContextRef g_context = JSContextGetGlobalContext(context); + + LogDebug("entered. Context : " << context << "(global:" << g_context << "), Object: " << object); + + if (context != g_context) + { + context = g_context; + } + + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + if (!priv) { + LogDebug("creation private object"); + + Try { + using namespace WrtDeviceApis::Commons; + + Widget::Api::IWidgetPtr widget = + Api::WidgetFactory::createWidget(); + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + JSObjectRef preferences = + createPreferencesObject(context, + object, + widgetId); + if (!preferences) { + LogError("Failed to create preferences object"); + } + + WidgetPrivateObjectPtr widgetPriv(new WidgetPrivateObject); + widgetPriv->iwidget = widget; + widgetPriv->preferencesObject = preferences; + + priv = new JSWidgetPrivateObject(context, widgetPriv); + JSObjectSetPrivate(object, priv); + } + Catch(Commons::InvalidArgumentException){ + LogError("You should register widget id in ON_WIDGET_START"); + return; + } + Catch(DPL::Exception) { + LogError("Failed to create private object for JSWidget"); + return; + } + } +} + +void JSWidget::finalize(JSObjectRef object) +{ + LogDebug("entered"); + LogDebug("Object: " << object); + JSWidgetPrivateObject* priv = + static_cast(JSObjectGetPrivate(object)); + + if (priv) { + JSValueUnprotect(priv->getContext(), + priv->getObject()->preferencesObject); + + delete priv; + LogDebug("private object is released"); + } else { + LogDebug("private object wasn't created"); + } +} + +JSValueRef JSWidget::getAuthor(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + LogDebug("entered"); + + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthor()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getAuthorEmail(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthorEmail()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getAuthorHref(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthorHref()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getDescription(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getDescription()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getId(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getId()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getName(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getName()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getShortName(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getShortName()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getVersion()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getHeight(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + unsigned int height = getIWidget(object)->getHeight(); + if (0 == height) { + height = 1; + } + return converter.toJSValueRef(height); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getWidth(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + unsigned int width = getIWidget(object)->getWidth(); + if (0 == width) { + width = 1; + } + return converter.toJSValueRef(width); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +bool JSWidget::hasProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName) +{ + LogDebug("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + if (key == "preferences") { + return true; + } + } + Catch(Commons::InvalidArgumentException) { + LogDebug("Pair for given key doesnt exist"); + } + + Catch(Commons::ConversionException) { + LogError("Error on conversion"); + } + + Catch(Commons::NullPointerException) { + LogError("Error on pointer, null value"); + } + + Catch(Commons::PlatformException){ + LogError("PlatformException occured"); + } + return false; +} + +JSValueRef JSWidget::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LogDebug("Object: " << object); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + if (key == "preferences") { + Converter converter(context); + JSObjectRef pref = getPreferences(object); + if (!pref) { + LogError("Preferences object is NULL"); + return JSValueMakeUndefined(context); + } + return pref; + } + LogError("Property NOT supported: " << propertyName); + return JSValueMakeUndefined(context); + } + + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSWidget::setProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName, + JSValueRef /*jvalue*/, + JSValueRef* exception) +{ + LogDebug("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + if (key == "preferences") { + LogError("Object is read only"); + return true; + } + } + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + + return false; +} + +JSObjectRef JSWidget::callAsConstructor(JSContextRef context, + JSObjectRef /*constructor*/, + size_t /*argumentCount*/, + const JSValueRef /*arguments*/[], + JSValueRef* /*exception*/) +{ + LogDebug("widget constructor"); + return JSObjectMake(context, JSWidget::getClassRef(), NULL); +} + +#undef CATCH_EXCEPTION_NO_MODIFABLE +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +#undef CATCH_EXCEPTION_OUT_OF_RANGE +#undef CATCH_EXCEPTION_INVALID_ARG +} +} diff --git a/src_wearable/standards/W3C/Widget/JSWidget.h b/src_wearable/standards/W3C/Widget/JSWidget.h new file mode 100644 index 0000000..f1f979c --- /dev/null +++ b/src_wearable/standards/W3C/Widget/JSWidget.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file JSWidget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_WIDGET_H_ +#define _WRT_PLUGIN_JS_WIDGET_H_ + +#include +#include +#include + +namespace WrtPlugins { +namespace W3C { +class JSWidget +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + static JSObjectRef callAsConstructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getAuthor(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAuthorEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAuthorHref(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getShortName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getHeight(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getWidth(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; +} +} + +#endif /* _WRT_PLUGIN_JS_WIDGET_INTERFACE_H_ */ diff --git a/src_wearable/standards/W3C/Widget/plugin_config.cpp b/src_wearable/standards/W3C/Widget/plugin_config.cpp new file mode 100644 index 0000000..8588aca --- /dev/null +++ b/src_wearable/standards/W3C/Widget/plugin_config.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "plugin_config.h" + +namespace WrtPlugins { +namespace W3C { +template <> +WidgetDeclarations::ParamsMap WidgetDeclarations::m_params = + WrtPlugins::W3C::WidgetDeclarations::ParamsMap(); + +template <> +WidgetDeclarations::DeviceCapsMaps WidgetDeclarations::m_deviceCaps = + WrtPlugins::W3C::WidgetDeclarations::DeviceCapsMaps(); + +template <> +WidgetDeclarations::FeaturesMap WidgetDeclarations::m_features = { + { + "http://w3cWidgetInterface.com/w3c-widget-interface", + {} + } +}; + +template <> +WidgetDeclarations::FunctionsMap WidgetDeclarations::m_functions = + WrtPlugins::W3C::WidgetDeclarations::FunctionsMap(); +} // namespace Wac2_0 +} // namespace WrtPlugins diff --git a/src_wearable/standards/W3C/Widget/plugin_config.h b/src_wearable/standards/W3C/Widget/plugin_config.h new file mode 100644 index 0000000..13de247 --- /dev/null +++ b/src_wearable/standards/W3C/Widget/plugin_config.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef _WIDGET_PLUGIN_CONFIG_H_ +#define _WIDGET_PLUGIN_CONFIG_H_ + +#include + +namespace WrtPlugins { +namespace W3C { +enum class WidgetParamId +{}; + +enum class WidgetDeviceCapId +{}; + +enum class WidgetFunctionId +{}; + +typedef WrtDeviceApis::CommonsJavaScript::StaticDeclarations < + WidgetParamId, + WidgetDeviceCapId, + WidgetFunctionId> WidgetDeclarations; +} +} + +#endif // _WIDGET_PLUGIN_CONFIG_H_ diff --git a/src_wearable/standards/W3C/Widget/plugin_initializer.cpp b/src_wearable/standards/W3C/Widget/plugin_initializer.cpp new file mode 100644 index 0000000..31b507d --- /dev/null +++ b/src_wearable/standards/W3C/Widget/plugin_initializer.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file plugin_initializer.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include + +#include +#include +#include +#include +#include +#include + +#include "JSWidget.h" +#include "JSPreferences.h" + +#include "plugin_config.h" + +#define OBJECT_WIDGET "widget" +#define INTERFACE_WIDGET_NAME "Widget" + +using namespace WrtPlugins::W3C; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtPluginsApi; + +namespace Options { +class_definition_options_t WidgetOptions = { + JS_CLASS, + CREATE_INSTANCE, + NONE_NOTICE, + IGNORED, + NULL, + NULL, + NULL +}; + +class_definition_options_t WidgetInterfaceOptions = { + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + IGNORED, //ignored + NULL, + NULL, + NULL +}; +} + +//TODO: remove this after switch to wrt-plugin-installer +void on_widget_init_callback(feature_mapping_interface_t *mapping) +{ + _D("[W3C\\widget] on_widget_init_callback"); + + WrtPlugins::W3C::WidgetDeclarations::getMappingInterface(mapping); +} +//... + +void on_widget_start_callback(int widgetId) +{ + _D("[W3C\\widget] on_widget_start_callback (%d)", widgetId); + + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + _E("Wrt wrapper registration failed"); + return; + } +} + +void on_widget_stop_callback(int widgetId) +{ + _D("[W3C\\widget] on_widget_stop_callback (%d)", widgetId); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + _E("Wrt wrapper registration failed"); + return; + } +} + +void Register(PluginRegistration& r) +{ + Plugin* plugin = new Plugin(); + + auto widgetObject = ObjectFactory::createObjectWithInterface( + OBJECT_WIDGET, + (js_class_template_getter) WrtPlugins::W3C::JSWidget::getClassRef, + INTERFACE_WIDGET_NAME, + reinterpret_cast(WrtPlugins::W3C::JSWidget::callAsConstructor)); + + plugin->AddObject(widgetObject); + + r.Connect(on_widget_start_callback); + r.Connect(on_widget_stop_callback); + + r.AddPlugin(*plugin); +} + +void Unregister(PluginRegistration& r, Plugin* plugin) +{ + r.DisconnectAll(); + delete plugin; +} + +void GetProvidedFeatures(feature_mapping_interface_t *mapping) +{ + WrtPlugins::W3C::WidgetDeclarations::getMappingInterface(mapping); +} + +ExportedApi dll_api={Register, Unregister, GetProvidedFeatures}; + +//TODO: remove this after switch to wrt-plugin-installer +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_WIDGET_INIT(on_widget_init_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_GLOBAL, + INTERFACE_WIDGET_NAME, + (js_class_template_getter) WrtPlugins::W3C::JSWidget::getClassRef, + reinterpret_cast(WrtPlugins::W3C::JSWidget:: + callAsConstructor), + &Options::WidgetInterfaceOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE_PRODUCT( + WRT_JS_EXTENSION_OBJECT_GLOBAL, + OBJECT_WIDGET, + INTERFACE_WIDGET_NAME, + &Options::WidgetOptions) + +PLUGIN_CLASS_MAP_END +//... + +#undef OBJECT_WIDGET +#undef INTERFACE_WIDGET_NAME diff --git a/src_wearable/wrt-popup/CMakeLists.txt b/src_wearable/wrt-popup/CMakeLists.txt new file mode 100755 index 0000000..13a79cc --- /dev/null +++ b/src_wearable/wrt-popup/CMakeLists.txt @@ -0,0 +1,2 @@ +ADD_SUBDIRECTORY(ace) +ADD_SUBDIRECTORY(wrt) diff --git a/src_wearable/wrt-popup/ace/CMakeLists.txt b/src_wearable/wrt-popup/ace/CMakeLists.txt new file mode 100755 index 0000000..2ecd23d --- /dev/null +++ b/src_wearable/wrt-popup/ace/CMakeLists.txt @@ -0,0 +1,2 @@ +ADD_SUBDIRECTORY(popup-bin) +ADD_SUBDIRECTORY(popup-runner) diff --git a/src_wearable/wrt-popup/ace/popup-bin/CMakeLists.txt b/src_wearable/wrt-popup/ace/popup-bin/CMakeLists.txt new file mode 100644 index 0000000..f87483d --- /dev/null +++ b/src_wearable/wrt-popup/ace/popup-bin/CMakeLists.txt @@ -0,0 +1,64 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Janusz Kozerski (j.kozerski@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_DEP + dpl-efl + elementary + security-client + security-popup-validation + REQUIRED) + +set(WRT_POPUP_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/ace/popup-bin) + +set(WRT_POPUP_SOURCES + ${WRT_POPUP_SRC_DIR}/Popup.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_SRC_DIR} + ${WRT_POPUP_DEP_INCLUDE_DIRS} +) + +ADD_EXECUTABLE(${TARGET_POPUP_ACE} + ${WRT_POPUP_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + #LINK_FLAGS "-Wl,--as-needed -Wl" + SOVERSION ${PROJECT_API_VERSION} + VERSION ${PROJECT_VERSION} +) + +target_link_libraries(${TARGET_POPUP_ACE} + ${WRT_POPUP_DEP_LIBRARIES} + ${TARGET_POPUP_ACE_RUNNER_LIB} + ${WRT_POPUP_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_ACE} + DESTINATION bin +) diff --git a/src_wearable/wrt-popup/ace/popup-bin/Popup.cpp b/src_wearable/wrt-popup/ace/popup-bin/Popup.cpp new file mode 100644 index 0000000..56a7ebb --- /dev/null +++ b/src_wearable/wrt-popup/ace/popup-bin/Popup.cpp @@ -0,0 +1,465 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file Popup.c + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +/* + * This is just a example pop-up that shows how to use a new C-API in + * wrt-security. + * This pop-up should be re-implemented by members of NGWAP. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "popup-runner.h" +#include "Popup.h" + +namespace { // anonymous +static void set_validity_from_checkbox(struct ace_popup_data *pdp) +{ + if (NULL == pdp) { + LogError("pdp is NULL; return"); + return; + } + + if (pdp->always) { + LogDebug("Remember ALWAYS"); + pdp->remember_choice = ACE_ALWAYS; + return; + } + if (pdp->per_session) { + LogDebug("Remember PER_SESSION"); + pdp->remember_choice = ACE_PER_SESSION; + return; + } + LogDebug("Remember ONCE"); + pdp->remember_choice = ACE_ONCE; + return; +} + +static void on_done(void) +{ + // Quit the efl-mainloop + LogDebug("elm_exit()"); + elm_exit(); +} + +static void grant_answer(void *data, + Evas_Object * /* obj */, + void * /* event_info */) +{ + LogDebug("grant_answer"); + if (NULL == data) { + LogError("data is NULL; return"); + return; + } + struct ace_popup_data *pdp = static_cast (data); + + set_validity_from_checkbox(pdp); + + ace_popup_validation_initialize(); + pdp->validation_return = ace_validate_answer( + ACE_TRUE, + pdp->remember_choice, + pdp->resource_name, + pdp->session_id, + &(pdp->param_list), + pdp->handle, + &(pdp->validation_result)); + ace_popup_validation_shutdown(); + + on_done(); +} + +static void deny_answer(void *data, + Evas_Object * /* obj */, + void * /* event_info */) +{ + LogDebug("deny_answer"); + if (NULL == data) { + LogError("data is NULL; return"); + return; + } + struct ace_popup_data *pdp = static_cast (data); + + set_validity_from_checkbox(pdp); + + ace_popup_validation_initialize(); + pdp->validation_return = ace_validate_answer( + ACE_FALSE, + pdp->remember_choice, + pdp->resource_name, + pdp->session_id, + &(pdp->param_list), + pdp->handle, + &(pdp->validation_result)); + ace_popup_validation_shutdown(); + + on_done(); +} + +static int _ace_params_deserializer(ace_param_list_t* ace_param_list, + Wrt::Popup::BinaryStream *stream) +{ + LogDebug("_ace_params_deserializer"); + + if (NULL == ace_param_list || NULL == stream) { + LogError("ace_param_list or stream is NULL; return -1"); + return -1; + } + + // deserialize ace_param_list->count; + size_t count = 0; + DPL::Deserialization::Deserialize(*stream, count); + ace_param_list->count = count; + LogDebug("count : " << count); + + std::string name; + std::string value; + if (count == 0) { + ace_param_list->items = NULL; + return 0; + } + ace_param_list->items = + static_cast (malloc(count * sizeof(ace_param_t))); + memset(ace_param_list->items, 0, count * sizeof(ace_param_t)); + + for (size_t i = 0; i < count; ++i) { + DPL::Deserialization::Deserialize(*stream, name); + ace_param_list->items[i].name = + strdup(const_cast (name.c_str())); + + DPL::Deserialization::Deserialize(*stream, value); + ace_param_list->items[i].value = + strdup(const_cast (value.c_str())); + } + return 0; +} + +static void _ace_params_finalize(ace_param_list_t* ace_param_list) +{ + if (!ace_param_list || !ace_param_list->items) { + LogDebug("List is null, nothing to do"); + return; + } + for (size_t i = 0; i < ace_param_list->count; ++i) { + free(ace_param_list->items[i].name); + free(ace_param_list->items[i].value); + } + free(ace_param_list->items); + ace_param_list->items = NULL; + ace_param_list->count = 0; +} + +static void show_popup(struct ace_popup_data *pdp) +{ + LogDebug("show_popup()"); + + if (NULL == pdp) { + LogError("pdp is NULL; return"); + return; + } + + const char *resource_type = static_cast (pdp->resource_name); + + Evas_Object *win = NULL; + Evas_Object *box = NULL; + Evas_Object *label = NULL; + Evas_Object *grant_button = NULL; + Evas_Object *deny_button = NULL; + pdp->per_session = EINA_FALSE; + pdp->always = EINA_FALSE; + + win = elm_win_add(NULL, "The wrt-client popup", ELM_WIN_NOTIFICATION); + elm_win_autodel_set(win, EINA_TRUE); + elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); + evas_object_show(win); + elm_win_indicator_opacity_set(win, ELM_WIN_INDICATOR_TRANSLUCENT); + + pdp->popup = elm_popup_add(win); + + box = elm_box_add(pdp->popup); + evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, 0); + evas_object_size_hint_align_set(box, EVAS_HINT_FILL, 0.0); + + label = elm_label_add(pdp->popup); + elm_object_style_set(label, "popup_description/default"); + elm_label_line_wrap_set(label, ELM_WRAP_MIXED); + char *buff = NULL; + if (-1 == + asprintf(&buff, "Application need an access to %s.
Grant or deny?", + resource_type)) + { + LogError("asprintf failed - returned -1"); + evas_object_del(label); + evas_object_del(pdp->popup); + evas_object_del(win); + return; + } + elm_object_text_set(label, buff); + free(buff); + evas_object_size_hint_weight_set(label, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(label, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(label); + elm_box_pack_end(box, label); + + LogDebug("popup_type == " << pdp->popup_type); + if (pdp->popup_type == ACE_SESSION || pdp->popup_type == ACE_BLANKET) { + LogDebug("popup_type == ACE_SESSION || ACE_BLANKET"); + Evas_Object *cb_session = elm_check_add(pdp->popup); + elm_object_text_set(cb_session, "Remember choice for this session"); + elm_check_state_pointer_set(cb_session, &(pdp->per_session)); + evas_object_smart_callback_add(cb_session, "changed", NULL, NULL); + evas_object_size_hint_align_set(cb_session, + EVAS_HINT_FILL, + EVAS_HINT_FILL); + evas_object_size_hint_weight_set(cb_session, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + evas_object_show(cb_session); + elm_box_pack_end(box, cb_session); + + if (pdp->popup_type == ACE_BLANKET) { + LogDebug("popup_type == ACE_BLANKET"); + Evas_Object *cb_always = elm_check_add(pdp->popup); + elm_object_text_set(cb_always, "Remember choice forever"); + elm_check_state_pointer_set(cb_always, &(pdp->always)); + evas_object_smart_callback_add(cb_always, "changed", NULL, NULL); + evas_object_size_hint_align_set(cb_always, + EVAS_HINT_FILL, + EVAS_HINT_FILL); + evas_object_size_hint_weight_set(cb_always, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + evas_object_show(cb_always); + elm_box_pack_end(box, cb_always); + } + } + + elm_object_part_content_set(pdp->popup, "default", box); + + grant_button = elm_button_add(pdp->popup); + elm_object_style_set(grant_button, "popup"); + elm_object_text_set(grant_button, "Grant"); + elm_object_part_content_set(pdp->popup, "button1", grant_button); + evas_object_smart_callback_add(grant_button, "clicked", grant_answer, pdp); + + deny_button = elm_button_add(pdp->popup); + elm_object_style_set(deny_button, "popup"); + elm_object_text_set(deny_button, "Deny"); + elm_object_part_content_set(pdp->popup, "button2", deny_button); + evas_object_smart_callback_add(deny_button, "clicked", deny_answer, pdp); + + evas_object_show(pdp->popup); + + // Showing the popup window + evas_object_show(win); + + // Run the efl mainloop + elm_run(); +} +} // anonymous + +EAPI_MAIN int +elm_main(int argc, char ** argv) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // int pipe_in and int pipe_out should be passed to Popup via args. + + // These parameters should be passed to Popup via pipe: + // ace_popup_t popup_type + // const ace_resource_t resource_name + // const ace_session_id_t session_id + // ace_widget_handle_t handle + // const ace_param_list_t param_list + + try { + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT-POPUP-BIN"); + } Catch(DPL::Exception) { + //cannot run logger + return ACE_INTERNAL_ERROR; + } + LogDebug( + "############################ popup binary ################################"); + + if (argc < 3) { + LogError( + "To few args passed in exec to popup-bin - should be at least 3:"); + LogError("(binary-name, pipe_in, pipe_out)"); + LogError("return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + LogDebug("Passed args: " << argv[0] << ", " << argv[1] << ", " << + argv[2]); + + int pipe_in; + int pipe_out; + std::stringstream parsing_stream; + + // Parsing args (pipe_in, pipe_out) + parsing_stream.str(argv[1]); + parsing_stream >> pipe_in; + if ( parsing_stream.fail() ) { + LogError("Error while parsing pipe_in; return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + parsing_stream.clear(); + parsing_stream.str(argv[2]); + parsing_stream >> pipe_out; + if ( parsing_stream.fail() ) { + LogError("Error while parsing pipe_out; return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + parsing_stream.clear(); + LogDebug("Parsed pipes: IN: " << pipe_in << ", OUT: " << pipe_out); + + int buff_size = 1024; + char line[buff_size]; + + struct ace_popup_data pd; + struct ace_popup_data *pdp = &pd; + + pdp->popup = NULL; + + ssize_t count = 0; + time_t time_start; + time(&time_start); // now + double timeout = 10.0; + // try to read parameters from pipe_in + // timeout is set for 10 seconds + do { + count = TEMP_FAILURE_RETRY(read(pipe_in, line, buff_size)); + if (timeout < difftime(time(NULL), time_start) ) { + LogError("Timeout reached! Exit popup - ACE_INTERNAL_ERROR"); + close(pipe_in); + close(pipe_out); + return ACE_INTERNAL_ERROR; + } + } while (0 == count); + if (count < 0) { + close(pipe_in); + close(pipe_out); + LogError("read returned a negative value (" << count << ")"); + LogError("errno: " << strerror(errno) ); + LogError("Exit popup - ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + LogDebug("Read bytes : " << count << " (in " << + difftime(time_start, time(NULL)) << " seconds)"); + close(pipe_in); // cleanup + + Wrt::Popup::BinaryStream stream; + stream.Write(count, static_cast (line)); + int popup_type = ACE_ONESHOT; + std::string resource_name_str; + std::string session_id_str; + int handle = 0; + + LogDebug("------- Deserialization -------"); + // Deserialization order: + // popup_type, resource_name, session_id, handle, param_list + + DPL::Deserialization::Deserialize(stream, popup_type); + LogDebug("popup_type_int : " << popup_type); + pdp->popup_type = static_cast (popup_type); + + DPL::Deserialization::Deserialize(stream, resource_name_str); + LogDebug("resource_name_char : " << resource_name_str.c_str()); + pdp->resource_name = + strdup(const_cast (resource_name_str.c_str())); + + DPL::Deserialization::Deserialize(stream, session_id_str); + LogDebug("session_id_char : " << session_id_str.c_str()); + pdp->session_id = + strdup(const_cast (session_id_str.c_str())); + + DPL::Deserialization::Deserialize(stream, handle); + LogDebug("handle_int : " << handle); + pdp->handle = static_cast (handle); + + if (_ace_params_deserializer(&(pdp->param_list), &stream)) { + return ACE_INTERNAL_ERROR; + } + + pdp->per_session = EINA_FALSE; + pdp->always = EINA_FALSE; + pdp->validation_return = ACE_ACE_UNKNOWN_ERROR; + + show_popup(pdp); // Showing popup + + // sending validation_result to popup-runner + Wrt::Popup::BinaryStream stream_out; + + LogDebug("pdp->validation_result : " << pdp->validation_result); + int validation_result_int = (int) pdp->validation_result; + LogDebug("validation_result_int : " << validation_result_int); + DPL::Serialization::Serialize(stream_out, validation_result_int); + if (-1 == + TEMP_FAILURE_RETRY(write(pipe_out, stream_out.char_pointer(), + stream_out.size()))) + { + LogError("Write to pipe failed!"); + close(pipe_out); + return ACE_INTERNAL_ERROR; + } + close(pipe_out); + + if (pdp->validation_return == ACE_OK) { + LogDebug("ACE_OK"); + } else if (pdp->validation_return == ACE_INVALID_ARGUMENTS) { + LogError("ACE_INVALID_ARGUMENTS"); + } else if (pdp->validation_return == ACE_INTERNAL_ERROR) { + LogError("ACE_INTERNAL_ERROR"); + } else if (pdp->validation_return == ACE_ACE_UNKNOWN_ERROR) { + LogError("ACE_ACE_UNKNOWN_ERROR"); + } else { + LogError("Really unknown error!!!"); + } + + LogDebug( + "############################ /popup binary ################################"); + + // Shutdown elementary + //LogDebug("elm_shutdown()"); + //elm_shutdown(); + // This is commented because, it causes that popup exits with 139 code + // (Segmentatation violation). + // Not calling elm_shutdown() should not have any negative consequences + // because this binary ends + // in next line, and system should clear the memory. + + _ace_params_finalize(&(pdp->param_list)); + return pdp->validation_return; + } + UNHANDLED_EXCEPTION_HANDLER_END +} +ELM_MAIN() diff --git a/src_wearable/wrt-popup/ace/popup-bin/Popup.h b/src_wearable/wrt-popup/ace/popup-bin/Popup.h new file mode 100644 index 0000000..388c921 --- /dev/null +++ b/src_wearable/wrt-popup/ace/popup-bin/Popup.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file Popup.h + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +#include +#include + +struct ace_popup_data { + ace_popup_t popup_type; + ace_resource_t resource_name; + ace_session_id_t session_id; + ace_param_list_t param_list; + ace_widget_handle_t handle; + ace_bool_t validation_result; + ace_return_t validation_return; + + Evas_Object *popup; + Eina_Bool per_session; + Eina_Bool always; + + ace_validity_t remember_choice; +}; diff --git a/src_wearable/wrt-popup/ace/popup-runner/CMakeLists.txt b/src_wearable/wrt-popup/ace/popup-runner/CMakeLists.txt new file mode 100644 index 0000000..4e5053c --- /dev/null +++ b/src_wearable/wrt-popup/ace/popup-runner/CMakeLists.txt @@ -0,0 +1,65 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Janusz Kozerski (j.kozerski@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_RUNNER_LIB_DEP + dpl-efl + elementary + security-client + REQUIRED) + +set(WRT_POPUP_RUNNER_LIB_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/ace/popup-runner) + +set(WRT_POPUP_RUNNER_LIB_SOURCES + ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/popup-runner.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_RUNNER_LIB_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_RUNNER_LIB_SRC_DIR} + ${WRT_POPUP_RUNNER_LIB_DEP_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_POPUP_ACE_RUNNER_LIB} SHARED + ${WRT_POPUP_RUNNER_LIB_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_POPUP_ACE_RUNNER_LIB} + ${WRT_POPUP_RUNNER_LIB_DEP_LIBRARIES} + ${WRT_POPUP_RUNNER_LIB_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_ACE_RUNNER_LIB} + DESTINATION lib +) + +INSTALL(FILES ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/popup-runner.h + DESTINATION ${DESTINATION_HEADERS_WRT_POPUP_RUNNER} +) diff --git a/src_wearable/wrt-popup/ace/popup-runner/popup-runner.cpp b/src_wearable/wrt-popup/ace/popup-runner/popup-runner.cpp new file mode 100644 index 0000000..e46fc16 --- /dev/null +++ b/src_wearable/wrt-popup/ace/popup-runner/popup-runner.cpp @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup-runner.cpp + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +/* + * This is just a example pop-up that shows how to use a new C-API in + * wrt-security. + * This pop-up should be re-implemented by members of NGWAP. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "popup-runner.h" + +namespace { // anonymous +const char *POPUP_EXEC = "/usr/bin/wrt-popup-ace-runtime"; + +void _ace_params_serializer (const ace_param_list_t* ace_param_list, + Wrt::Popup::BinaryStream *stream) +{ + LogDebug("_ace_params_serializer"); + + if (NULL == ace_param_list || NULL == stream) { + LogError("*ace_param_list or *stream is NULL; return"); + return; + } + LogDebug("Param count : " << ace_param_list->count); + + // serialize ace_param_list->count; + size_t count = static_cast (ace_param_list->count); + DPL::Serialization::Serialize(*stream, count); + + for (size_t i = 0; i < count; ++i) { + std::string name(ace_param_list->items[i].name); + DPL::Serialization::Serialize(*stream, name); + + std::string value(ace_param_list->items[i].value); + DPL::Serialization::Serialize(*stream, value); + } +} +} // anonymous namespace + +namespace Wrt { +namespace Popup { +// BinaryStream class implementation +void BinaryStream::Read(size_t num, void * bytes) +{ + size_t max_size = m_data.size(); + for (size_t i = 0; i < num; ++i) { + if (i + m_readPosition >= max_size) { + return; + } + static_cast (bytes)[i] = m_data[i + m_readPosition]; + } + m_readPosition += num; +} + +void BinaryStream::Write(size_t num, const void * bytes) +{ + for (size_t i = 0; i < num; ++i) { + m_data.push_back(static_cast (bytes)[i]); + } +} + +BinaryStream::BinaryStream() +{ + m_readPosition = 0; +} + +BinaryStream::~BinaryStream() {} + +const unsigned char* BinaryStream::char_pointer() const +{ + return &m_data[0]; +} + +size_t BinaryStream::size() const +{ + return m_data.size(); +} +// BinaryStream + +ace_return_t run_popup( + ace_popup_t popup_type, + const ace_resource_t resource_name, + const ace_session_id_t session_id, + const ace_param_list_t* ace_param_list, + ace_widget_handle_t handle, + ace_bool_t* validation_result) +{ + if (NULL == resource_name || + NULL == session_id || + NULL == ace_param_list || + NULL == validation_result) + { + LogError("run_popup : ACE_INVALID_ARGUMENTS"); + return ACE_INVALID_ARGUMENTS; + } + LogDebug("popup_type : " << popup_type); + LogDebug("resource_name : " << resource_name); + LogDebug("session_id : " << session_id); + LogDebug("widget handle : " << handle); + + int popup_type_int = static_cast (popup_type); + char *resource_name_char = static_cast (resource_name); + char *session_id_char = static_cast (session_id); + int handle_int = static_cast (handle); + + // serialization + Wrt::Popup::BinaryStream stream; + DPL::Serialization::Serialize(stream, popup_type_int); + + std::string resource_name_str(resource_name_char); + DPL::Serialization::Serialize(stream, resource_name_str); + + std::string session_id_str(session_id_char); + DPL::Serialization::Serialize(stream, session_id_str); + + DPL::Serialization::Serialize(stream, handle_int); + + _ace_params_serializer(ace_param_list, &stream); + + int fd_send_to_child[2]; + int fd_send_to_parent[2]; + pid_t childpid; + + if (0 != pipe(fd_send_to_child)) { + LogError("Cannot create pipes!"); + return ACE_INTERNAL_ERROR; + } + if (0 != pipe(fd_send_to_parent)) { + LogError("Cannot create pipes!"); + return ACE_INTERNAL_ERROR; + } + + if ((childpid = fork()) == -1) { + LogError("Fork() ERROR"); + return ACE_ACE_UNKNOWN_ERROR; + } + + if (childpid == 0) { // Child process + LogDebug("Child"); + + // read data from parent + close(fd_send_to_child[1]); + + // send data to parent + close(fd_send_to_parent[0]); + + std::stringstream pipe_in_buff; + std::stringstream pipe_out_buff; + pipe_in_buff << fd_send_to_parent[1]; + pipe_out_buff << fd_send_to_child[0]; + std::string pipe_in = pipe_in_buff.str(); + std::string pipe_out = pipe_out_buff.str(); + + LogDebug( + "Passed file descriptors: " << fd_send_to_child[0] << ", " << + fd_send_to_parent[1]); + + if (execl(POPUP_EXEC, POPUP_EXEC, pipe_out.c_str(), pipe_in.c_str(), + NULL) < 0) + { + LogError("execlp FAILED"); + } + + LogError("This should not happened!!!"); + } // end of child process - from now you can use DEBUG LOGS + else { // Parent process + LogDebug("Parent"); + + int buff_size = 1024; + char result[buff_size]; + // send data to child + close(fd_send_to_child[0]); + + //writing to child + LogDebug("Sending message to popup-bin process"); + if (-1 == + TEMP_FAILURE_RETRY(write(fd_send_to_child[1], stream.char_pointer(), + stream.size()))) + { + LogError("Write to pipe failed!"); + return ACE_INTERNAL_ERROR; + } + close(fd_send_to_child[1]); // cleanup + LogDebug("Message has been sent"); + + // read data from child + close(fd_send_to_parent[1]); + + int status; + wait(&status); + LogDebug("STATUS EXIT ON POPUP (CHILD): " << status); + switch (status) { + case ACE_OK: + LogDebug("ACE_OK"); + break; + + case ACE_INVALID_ARGUMENTS: + LogDebug("ACE_INVALID_ARGUMENTS"); + close(fd_send_to_parent[0]); + return static_cast (status); + break; + + case ACE_INTERNAL_ERROR: + LogDebug("ACE_INTERNAL_ERROR"); + close(fd_send_to_parent[0]); + return static_cast (status); + break; + + case ACE_ACE_UNKNOWN_ERROR: + LogDebug("ACE_ACE_UNKNOWN_ERROR"); + close(fd_send_to_parent[0]); + return static_cast (status); + break; + + default: + LogDebug("UNKNOWN_ERROR"); + close(fd_send_to_parent[0]); + status = (int) ACE_ACE_UNKNOWN_ERROR; + return static_cast (status); + break; + } + + int count; + count = TEMP_FAILURE_RETRY(read(fd_send_to_parent[0], result, buff_size)); + close(fd_send_to_parent[0]); // cleanup + + + if (0 < count) { + BinaryStream stream_in; + int validation_result_int; + stream_in.Write(count, result); + LogDebug("RESULT FROM POPUP (CHILD) : [ " << count << " ]"); + DPL::Deserialization::Deserialize(stream_in, validation_result_int); + *validation_result = static_cast (validation_result_int); + + LogDebug("validation_result :"); + switch (*validation_result) { + case ACE_FALSE: + LogDebug("ACE_FALSE"); + break; + case ACE_TRUE: + LogDebug("ACE_TRUE"); + break; + default: + LogDebug("UNKNOWN - DEFAULT"); + break; + } + } else { + LogDebug("count = " << count); + LogDebug("UNKNOWN_ERROR"); + return ACE_ACE_UNKNOWN_ERROR; + } + + LogDebug("popup-runner: EXIT"); + return (ace_return_t) status; + } + + LogError("This should not happend!!!"); + return ACE_ACE_UNKNOWN_ERROR; +} +} // Popup +} // Wrt diff --git a/src_wearable/wrt-popup/ace/popup-runner/popup-runner.h b/src_wearable/wrt-popup/ace/popup-runner/popup-runner.h new file mode 100644 index 0000000..d136fb1 --- /dev/null +++ b/src_wearable/wrt-popup/ace/popup-runner/popup-runner.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup-runner.h + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +#include +#include + +#include + +namespace Wrt { +namespace Popup { +class BinaryStream : public DPL::IStream +{ + public: + void Read (size_t num, void * bytes); + void Write(size_t num, const void * bytes); + + BinaryStream(); + ~BinaryStream(); + + const unsigned char* char_pointer() const; + size_t size() const; + + private: + std::vector m_data; + size_t m_readPosition; +}; + +ace_return_t run_popup( + ace_popup_t popup_type, + const ace_resource_t resource_name, + const ace_session_id_t session_id, + const ace_param_list_t* ace_param_list, + ace_widget_handle_t handle, + ace_bool_t* validation_result + ); +} // Popup +} // Wrt diff --git a/src_wearable/wrt-popup/wrt/CMakeLists.txt b/src_wearable/wrt-popup/wrt/CMakeLists.txt new file mode 100755 index 0000000..ed0e24b --- /dev/null +++ b/src_wearable/wrt-popup/wrt/CMakeLists.txt @@ -0,0 +1,9 @@ + +set(WRT_POPUP_COMMON_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/wrt) + +SET(WRT_POPUP_COMMON_SRCS + ${WRT_POPUP_COMMON_DIR}/PopupSerializer.cpp +) + +ADD_SUBDIRECTORY(popup-bin) +ADD_SUBDIRECTORY(popup-runner) diff --git a/src_wearable/wrt-popup/wrt/PopupEnum.h b/src_wearable/wrt-popup/wrt/PopupEnum.h new file mode 100644 index 0000000..3200ef4 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/PopupEnum.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_ENUM_H +#define WRT_POPUP_ENUM_H + +namespace Wrt { +enum PopupType { + INFO_PROMPT = 1, + YES_NO_PROMPT, + YES_NO_CHECK_PROMPT +}; +} + +#endif + diff --git a/src_wearable/wrt-popup/wrt/PopupSerializer.cpp b/src_wearable/wrt-popup/wrt/PopupSerializer.cpp new file mode 100644 index 0000000..e9dd99f --- /dev/null +++ b/src_wearable/wrt-popup/wrt/PopupSerializer.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "PopupSerializer.h" + +#include + +namespace Wrt { +namespace PopupSerializer { +void appendArg(int arg, DPL::BinaryQueue &buffer) +{ + size_t argSize = sizeof(arg); + buffer.AppendCopy(&argSize, sizeof(argSize)); + buffer.AppendCopy(&arg, sizeof(arg)); +} + +void appendArg(const std::string &arg, DPL::BinaryQueue &buffer) +{ + size_t argSize = arg.size(); + buffer.AppendCopy(&argSize, sizeof(argSize)); + buffer.AppendCopy(arg.c_str(), argSize); +} + +int getIntArg(DPL::BinaryQueue &buffer) +{ + int result; + size_t argSize; + buffer.FlattenConsume(&argSize, sizeof(argSize)); + buffer.FlattenConsume(&result, argSize); + //TODO: what if argSize != sizeof(int) + //This should not be problem if this is run on the same machine. + return result; +} + +std::string getStringArg(DPL::BinaryQueue &buffer) +{ + std::string::size_type size; + buffer.FlattenConsume(&size, sizeof(size)); + std::unique_ptr str(new char[size]); + buffer.FlattenConsume(str.get(), size); + return std::string(str.get(), str.get() + size); +} +} +} // Wrt diff --git a/src_wearable/wrt-popup/wrt/PopupSerializer.h b/src_wearable/wrt-popup/wrt/PopupSerializer.h new file mode 100644 index 0000000..70407ec --- /dev/null +++ b/src_wearable/wrt-popup/wrt/PopupSerializer.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_SERIALIZER_H +#define WRT_POPUP_SERIALIZER_H + +#include +#include + +namespace Wrt { +namespace PopupSerializer { +void appendArg(int arg, DPL::BinaryQueue &buffer); +void appendArg(const std::string &arg, DPL::BinaryQueue &buffer); + +int getIntArg(DPL::BinaryQueue &buffer); +std::string getStringArg(DPL::BinaryQueue &buffer); +} +} // Wrt + +#endif \ No newline at end of file diff --git a/src_wearable/wrt-popup/wrt/popup-bin/CMakeLists.txt b/src_wearable/wrt-popup/wrt/popup-bin/CMakeLists.txt new file mode 100644 index 0000000..52f73ff --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/CMakeLists.txt @@ -0,0 +1,56 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +PKG_CHECK_MODULES(WRT_POPUP_DEPS + ecore-x + dpl-efl + dpl-event-efl + REQUIRED +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/renderer + ${WRT_POPUP_DEPS_INCLUDE_DIRS} + ${WRT_POPUP_COMMON_DIR} +) + +SET(WRT_POPUP_SRCS + ${WRT_POPUP_COMMON_SRCS} + wrt-popup.cpp + YesNoPopup.cpp + YesNoCheckPopup.cpp + InfoPopup.cpp + renderer/evas_object.cpp + renderer/popup_controller.cpp + renderer/popup_manager.cpp + renderer/popup_renderer.cpp +) + +ADD_EXECUTABLE(${TARGET_POPUP_WRT} + ${WRT_POPUP_SRCS} +) + +TARGET_LINK_LIBRARIES(${TARGET_POPUP_WRT} + ${WRT_POPUP_DEPS_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT} PROPERTIES + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON +) + +INSTALL(TARGETS ${TARGET_POPUP_WRT} DESTINATION bin) diff --git a/src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.cpp b/src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.cpp new file mode 100644 index 0000000..4536350 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file InfoPopup.cpp + * @author Lukasz Marek(l.marek@samsung.com) + * @version 1.0 + * @brief Popup that displays information. Inplementation + */ + +#include "InfoPopup.h" +#include +#include +#include "popup_manager.h" +#include "popup.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +InfoPopup::InfoPopup() : + m_parent(NULL) +{} + +void InfoPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) +{ + LogDebug("Entered"); + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + std::string button = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + LogDebug("title: " << title << " message: " << message); + + m_parent = parent; + + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + + popup->Append(new Renderer::PopupObject::Button(button, 0)); + + ListenForAnswer(popup); + + Renderer::ShowPopupEventShort event(popup, + MakeAnswerCallback( + this, + &InfoPopup::responseCallback)); + + CONTROLLER_POST_EVENT(Renderer::PopupController, + event); + + LogDebug("Exited"); + return; +} + +void InfoPopup::responseCallback(const Renderer::AnswerCallbackData &answer) +{ + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(answer.buttonAnswer, retValue); + m_parent->response(retValue); +} +} // Popup +} // Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.h b/src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.h new file mode 100644 index 0000000..3a29fc0 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/InfoPopup.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file InfoPopup.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons + */ + +#ifndef WRT_INFO_POPUP_H +#define WRT_INFO_POPUP_H + +#include "wrt-popup.h" + +namespace Wrt { +namespace Popup { +class InfoPopup : public IPopup +{ + public: + InfoPopup(); + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent); + + private: + + void responseCallback(const Renderer::AnswerCallbackData &answer); + WrtPopup* m_parent; +}; +} // Popup +} // Wrt + +#endif /* WRT_INFO_POPUP_H */ + diff --git a/src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp b/src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp new file mode 100644 index 0000000..7cdbf73 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp @@ -0,0 +1,51 @@ +/* + * File: YesNoCheckPopup.cpp + * Author: pciezkowski + * + * Created on December 12, 2012, 9:23 AM + */ + +#include "YesNoCheckPopup.h" +#include +#include +#include "popup_manager.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +YesNoCheckPopup::~YesNoCheckPopup() +{} + +Renderer::CtrlPopupPtr YesNoCheckPopup::createPopup( + DPL::BinaryQueueAutoPtr data) +{ + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + std::string checkboxLabel = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + LogDebug("title: " << title << " message: " << message << " checkbox: " << + checkboxLabel); + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + popup->Append(new Renderer::PopupObject::Check(checkboxLabel)); + popup->Append(new Renderer::PopupObject::Button(YES_LABEL, POPUP_YES_VALUE)); + popup->Append(new Renderer::PopupObject::Button(NO_LABEL, POPUP_NO_VALUE)); + return popup; +} + +void YesNoCheckPopup::responseCallback( + const Renderer::AnswerCallbackData &answer) +{ + bool result = (POPUP_YES_VALUE == answer.buttonAnswer); + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(result, retValue); + LogDebug("Check state: " << answer.chackState); + PopupSerializer::appendArg(answer.chackState, retValue); + m_parent->response(retValue); +} +} // Popup +} // Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h b/src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h new file mode 100644 index 0000000..9012df5 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file YesNoCheckPopup.cpp + * @author Przmeyslaw Ciezkowsko (p.ciezkowski@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons and checkbox. + * Inplementation + */ + +#include "YesNoPopup.h" +#include "wrt-popup.h" + +#ifndef WRT_YES_NO_CHECK_POPUP_H +#define WRT_YES_NO_CHECK_POPUP_H + +namespace Wrt { +namespace Popup { +class YesNoCheckPopup : public YesNoPopup +{ + public: + virtual ~YesNoCheckPopup(); + + protected: + virtual Renderer::CtrlPopupPtr createPopup(DPL::BinaryQueueAutoPtr data); + virtual void responseCallback(const Renderer::AnswerCallbackData &answer); +}; +} // Popup +} // Wrt + +#endif /* WRT_YES_NO_CHECK_POPUP_H */ + diff --git a/src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.cpp b/src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.cpp new file mode 100644 index 0000000..a47d205 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file YesNoPopup.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons. Inplementation + */ + +#include "YesNoPopup.h" +#include +#include +#include "popup_manager.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +void YesNoPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) +{ + LogDebug("Entered"); + m_parent = parent; + Renderer::CtrlPopupPtr popup = createPopup(data); + ListenForAnswer(popup); + + Renderer::ShowPopupEventShort event(popup, + MakeAnswerCallback( + this, + &YesNoPopup::responseCallback)); + + CONTROLLER_POST_EVENT(Renderer::PopupController, + event); + + LogDebug("Exited"); + return; +} + +void YesNoPopup::responseCallback(const Renderer::AnswerCallbackData &answer) +{ + bool result = (POPUP_YES_VALUE == answer.buttonAnswer); + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(result, retValue); + m_parent->response(retValue); +} + +YesNoPopup::~YesNoPopup() +{} + +Renderer::CtrlPopupPtr YesNoPopup::createPopup(DPL::BinaryQueueAutoPtr data) +{ + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + LogDebug("title: " << title << " message: " << message); + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + + popup->Append(new Renderer::PopupObject::Button(YES_LABEL, POPUP_YES_VALUE)); + popup->Append(new Renderer::PopupObject::Button(NO_LABEL, POPUP_NO_VALUE)); + return popup; +} +} // Popup +} // Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.h b/src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.h new file mode 100644 index 0000000..5dbe2f8 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/YesNoPopup.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file YesNoPopup.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons + */ + +#ifndef WRT_YES_NO_POPUP_H +#define WRT_YES_NO_POPUP_H + +#include "wrt-popup.h" + +namespace Wrt { +namespace Popup { +const char YES_LABEL[] = "Yes"; +const char NO_LABEL[] = "No"; +const int POPUP_YES_VALUE = 1; +const int POPUP_NO_VALUE = 2; + +class YesNoPopup : public IPopup +{ + public: + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent); + virtual ~YesNoPopup(); + + protected: + virtual Renderer::CtrlPopupPtr createPopup(DPL::BinaryQueueAutoPtr data); + virtual void responseCallback(const Renderer::AnswerCallbackData &answer); + WrtPopup* m_parent; +}; +} // Popup +} // Wrt + +#endif /* WRT_YES_NO_POPUP_H */ + diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp b/src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp new file mode 100644 index 0000000..13b38c1 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file evas_object.cpp + * @author Lukasz Wrzosek (l.wrzosel@samsung.com) + * @version 1.0 + * @brief This file is the implementation for Evas_Object wrapper from + * Efl. + */ + +#include "evas_object.h" +#include +#include + +namespace Wrt { +namespace Popup { +namespace Renderer { +Evas_Object* EvasObject::IConnection::GetEvasObject() +{ + return m_object->GetObject(); +} + +void EvasObject::IConnection::Disconnect() +{ + m_object->DisconnectCallback(this); +} + +EvasObject::IConnection::IConnection(EvasObject::EvasObjectShared* object) : + m_object(object) +{} + +void EvasObject::IConnection::SmartCallbackWrapper(void* data, + Evas_Object* /*object*/, + void* event_info) +{ + Assert(data); + IConnection* Calle = static_cast(data); + Calle->Call(event_info); +} + +void EvasObject::IConnection::EvasCallbackWrapper(void* data, + Evas* /*evas*/, + Evas_Object* /*object*/, + void* event_info) +{ + Assert(data); + IConnection* Calle = static_cast(data); + Calle->Call(event_info); +} + +Evas_Object* EvasObject::EvasObjectShared::GetObject() +{ + return m_object; +} + +EvasObject::EvasObjectShared::SmartConnectionBase::SmartConnectionBase( + const std::string& name, + EvasObject::EvasObjectShared* object) : + IConnection(object), + m_callbackName(name) +{} + +void EvasObject::EvasObjectShared::SmartConnectionBase::ConnectPrv() +{ + evas_object_smart_callback_add(GetEvasObject(), + m_callbackName.c_str(), + &IConnection::SmartCallbackWrapper, this); +} + +void EvasObject::EvasObjectShared::SmartConnectionBase::DisconnectPrv() +{ + evas_object_smart_callback_del(GetEvasObject(), + m_callbackName.c_str(), + &IConnection::SmartCallbackWrapper); +} + +EvasObject::EvasObjectShared::EvasConnectionBase::EvasConnectionBase( + Evas_Callback_Type type, + EvasObject::EvasObjectShared* object) : + IConnection(object), + m_callbackType(type) +{} + +void EvasObject::EvasObjectShared::EvasConnectionBase::ConnectPrv() +{ + evas_object_event_callback_add( + GetEvasObject(), m_callbackType, &IConnection::EvasCallbackWrapper, + this); +} + +void EvasObject::EvasObjectShared::EvasConnectionBase::DisconnectPrv() +{ + evas_object_event_callback_del_full( + GetEvasObject(), m_callbackType, &IConnection::EvasCallbackWrapper, + this); +} + +EvasObject::EvasObjectShared::EvasObjectShared() : + m_object(NULL) +{} + +EvasObject::EvasObjectShared::EvasObjectShared(Evas_Object* object) : + m_object(object) +{ + Assert(m_object); + evas_object_event_callback_add(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent, + this); +} + +void EvasObject::EvasObjectShared::SetObject(Evas_Object* object) +{ + Assert(m_object == NULL); + Assert(object != NULL); + m_object = object; + evas_object_event_callback_add(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent, + this); +} + +EvasObject::EvasObjectShared::~EvasObjectShared() +{ + if (m_object) { + DisconnectAll(); + evas_object_event_callback_del(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent); + m_object = NULL; + } +} + +bool EvasObject::EvasObjectShared::DisconnectCallback(IConnection* connection) +{ + IConnectionsSet::iterator it = m_connections.find(connection); + if (it != m_connections.end()) { + (*it)->DisconnectPrv(); + delete connection; + m_connections.erase(it); + return true; + } + return false; +} + +void EvasObject::EvasObjectShared::DisconnectAll() +{ + FOREACH(it, m_connections) + { + (*it)->DisconnectPrv(); + delete *it; + } + m_connections.clear(); +} + +void EvasObject::EvasObjectShared::StaticOnDelEvent(void* data, + Evas* /*e*/, + Evas_Object* /*o*/, + void* /*ev*/) +{ + Assert(data); + EvasObjectShared* This = static_cast(data); + if (This->m_object) { + evas_object_event_callback_del(This->m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent); + This->DisconnectAll(); + This->m_object = NULL; + } +} + +EvasObject::EvasObject() : + m_object(new EvasObjectShared()) +{} + +EvasObject::EvasObject(Evas_Object* object) : + m_object(new EvasObjectShared(object)) +{} + +EvasObject::EvasObject(const EvasObject& other) : + m_object(other.m_object) +{} + +//this destructor must be here to let pimpl with shared_ptr work without warning +EvasObject::~EvasObject() +{} + +EvasObject& EvasObject::operator=(const EvasObject& other) +{ + Assert(m_object); + m_object = other.m_object; + return *this; +} + +EvasObject* EvasObject::operator=(Evas_Object* object) +{ + Assert(m_object); + m_object->SetObject(object); + return this; +} + +bool EvasObject::DisconnectCallback(IConnection* connection) +{ + Assert(m_object); + return m_object->DisconnectCallback(connection); +} + +void EvasObject::DisconnectAll() +{ + Assert(m_object); + m_object->DisconnectAll(); +} + +EvasObject::operator Evas_Object *() +{ + Assert(m_object); + return m_object->GetObject(); +} +} +} // namespace DPL +} // namespace Popup diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.h b/src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.h new file mode 100644 index 0000000..2758fa1 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/evas_object.h @@ -0,0 +1,654 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file evas_object.h + * @author Lukasz Wrzosek (l.wrzosel@samsung.com) + * @version 1.0 + * @brief This file is the header for Evas_Object wrapper from Efl. + */ + +#ifndef WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H +#define WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Wrt { +namespace Popup { +namespace Renderer { +class EvasObject +{ + class EvasObjectShared; + typedef std::shared_ptr EvasObjectSharedPtr; + + public: + class IConnection + { + public: + Evas_Object* GetEvasObject(); + void Disconnect(); + + private: + IConnection(EvasObjectShared* object); + virtual ~IConnection() + {} + virtual void Call(void* /*event_info*/) = 0; + + static void SmartCallbackWrapper(void* data, + Evas_Object* /*object*/, + void* event_info); + static void EvasCallbackWrapper(void* data, + Evas* /*evas*/, + Evas_Object* /*object*/, + void* event_info); + + virtual void ConnectPrv() = 0; + virtual void DisconnectPrv() = 0; + + friend class EvasObjectShared; + + EvasObjectShared* m_object; + }; + + private: + class EvasObjectShared : DPL::Noncopyable + { + public: + friend class IConnection; + Evas_Object* GetObject(); + + typedef std::set IConnectionsSet; + + class SmartConnectionBase : public IConnection + { + public: + SmartConnectionBase(const std::string& name, + EvasObjectShared* object); + + virtual void ConnectPrv(); + virtual void DisconnectPrv(); + std::string m_callbackName; + }; + + template + class SmartConnection : public SmartConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, + void* event_info, + Args ... args); + + SmartConnection(const std::string& name, + CbType callback, + EvasObjectShared* object, + Args ... args) : + SmartConnectionBase(name, object), + m_callback(callback), + m_args(args ...) + {} + + virtual ~SmartConnection() + {} + + virtual void Call(void* event_info) + { + DPL::Apply(m_callback, + m_args, + this, + event_info); + } + + private: + CbType m_callback; + std::tuple m_args; + }; + + template + class SmartMemberConnection1 : public SmartConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1); + + SmartMemberConnection1(const std::string& name, + CbType callback, + ThisType* callee, + ArgType1* arg1, + EvasObjectShared* object) : + SmartConnectionBase(name, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1) + {} + + virtual ~SmartMemberConnection1() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + }; + + template + class SmartMemberConnection2 : public SmartConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1, + ArgType2* arg2); + + SmartMemberConnection2(const std::string& name, + CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + SmartConnectionBase(name, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~SmartMemberConnection2() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + class EvasConnectionBase : public IConnection + { + public: + EvasConnectionBase(Evas_Callback_Type type, + EvasObjectShared* object); + + virtual void ConnectPrv(); + virtual void DisconnectPrv(); + + Evas_Callback_Type m_callbackType; + }; + + template + class EvasConnection1 : public EvasConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, void* event_info, + ArgType1 *arg1); + + EvasConnection1(Evas_Callback_Type type, + CbType callback, + ArgType1* arg1, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_arg1(arg1) + {} + + virtual ~EvasConnection1() + {} + + virtual void Call(void* event_info) + { + m_callback(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ArgType1* m_arg1; + }; + + template + class EvasConnection2 : public EvasConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, void* event_info, + ArgType1 *arg1, ArgType2 *arg2); + + EvasConnection2(Evas_Callback_Type type, + CbType callback, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~EvasConnection2() + {} + + virtual void Call(void* event_info) + { + m_callback(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + template + class EvasMemberConnection1 : public EvasConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1); + + EvasMemberConnection1(Evas_Callback_Type type, + CbType callback, + ThisType* callee, + ArgType1* arg1, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1) + {} + + virtual ~EvasMemberConnection1() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + }; + + template + class EvasMemberConnection2 : public EvasConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1* arg1, + ArgType2* arg2); + + EvasMemberConnection2(Evas_Callback_Type type, + CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~EvasMemberConnection2() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + EvasObjectShared(); + explicit EvasObjectShared(Evas_Object* object); + void SetObject(Evas_Object* object); + ~EvasObjectShared(); + + template + IConnection* ConnectSmartCallback( + const char* callbackName, + typename SmartConnection:: + CbType callback, + Args ... args) + { + Assert(m_object); + Assert(callbackName); + Assert(callback); + IConnection* connection = new SmartConnection( + callbackName, + callback, + this, + args ...); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename SmartMemberConnection2::CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callbackName); + Assert(callback); + IConnection* connection = + new SmartMemberConnection2( + callbackName, + callback, + callee, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename SmartMemberConnection1::CbType callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callbackName); + Assert(callback); + IConnection* connection = + new SmartMemberConnection1(callbackName, + callback, + callee, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectEvasCallback(Evas_Callback_Type callbackType, + typename EvasConnection2:: + CbType callback, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callbackType); + Assert(callback); + IConnection* connection = new EvasConnection2( + callbackType, + callback, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasConnection1:: + CbType callback, + ArgType1* arg1) + { + Assert(m_object); + Assert(callbackType); + Assert(callback); + IConnection* connection = new EvasConnection1( + callbackType, + callback, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasMemberConnection2::CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callbackType); + Assert(callback); + IConnection* connection = + new EvasMemberConnection2( + callbackType, + callback, + callee, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasMemberConnection1::CbType callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callbackType); + Assert(callback); + IConnection* connection = + new EvasMemberConnection1(callbackType, + callback, + callee, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + bool DisconnectCallback(IConnection* connection); + void DisconnectAll(); + + static void StaticOnDelEvent(void* data, + Evas* /*e*/, + Evas_Object* /*o*/, + void* /*ev*/); + + IConnectionsSet m_connections; + Evas_Object* m_object; + }; + + public: + EvasObject(); + explicit EvasObject(Evas_Object* object); + EvasObject(const EvasObject& other); + ~EvasObject(); + + EvasObject& operator=(const EvasObject& other); + EvasObject* operator=(Evas_Object* object); + + operator Evas_Object *(); + + bool IsValid() const + { + Assert(m_object); + return m_object->GetObject() != NULL; + } + + bool DisconnectCallback(IConnection* connection); + void DisconnectAll(); + + template + IConnection* ConnectSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartConnection::CbType + callback, + Args ... args) + { + Assert(m_object); + return m_object->ConnectSmartCallback(callbackName, callback, args ...); + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartMemberConnection2::CbType + callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberSmartCallback(callbackName, + callback, + callee, + arg1, + arg2); + } + + template + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartMemberConnection1::CbType + callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberSmartCallback(callbackName, + callback, + callee, + arg1); + } + + template + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasConnection1::CbType + callback, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + return m_object->ConnectEvasCallback(callbackType, callback, arg1, arg2); + } + + template + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasConnection1::CbType + callback, + ArgType1* arg1) + { + Assert(m_object); + return m_object->ConnectEvasCallback(callbackType, callback, arg1); + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasMemberConnection1::CbType + callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberEvasCallback(callbackType, + callback, + callee, + arg1); + } + + template + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasMemberConnection2::CbType + callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberEvasCallback(callbackType, + callback, + callee, + arg1, + arg2); + } + + private: + EvasObjectSharedPtr m_object; +}; +} +} //namespace +} //namespace + +#endif //WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H + diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup.h b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup.h new file mode 100644 index 0000000..0d9474b --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup inteface declaration + */ + +#ifndef WRT_SRC_POPUP_POPUP_H_ +#define WRT_SRC_POPUP_POPUP_H_ + +#include +#include +#include +#include +#include +#include "popup_object.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +struct AnswerCallbackData +{ + int buttonAnswer; + DPL::OptionalStdString password; + bool chackState; +}; + +class PopupManager; +class IPopup; +typedef std::shared_ptr IPopupPtr; + +class IPopup : public std::enable_shared_from_this +{ + public: + virtual void SetTitle(const std::string &title) = 0; + /*The object is deleted automatically after rendered */ + virtual void Append(PopupObject::IPopupObject *object) = 0; + + protected: + typedef void (*PopupCallbackType)(const AnswerCallbackData& answer, + void *data); + virtual void Show(PopupCallbackType callback, + void* data) = 0; + virtual ~IPopup() + {} + + private: + friend class PopupManager; + friend class std::shared_ptr; +}; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_H_ diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp new file mode 100644 index 0000000..b9bb5b3 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file popup_controller.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @bref Implementation file for popup controller + */ + +#include "popup_controller.h" +#include +#include +#include +#include + +IMPLEMENT_SINGLETON(Wrt::Popup::Renderer::PopupController) + +namespace Wrt { +namespace Popup { +namespace Renderer { +void CtrlPopup::SetTitle(const std::string &title) +{ + Assert(m_popup); + m_popup->SetTitle(title); +} + +void CtrlPopup::Append(PopupObject::IPopupObject *object) +{ + Assert(m_popup); + m_popup->Append(object); +} + +CtrlPopup::CtrlPopup(IPopupPtr popup) : + m_popup(popup), + m_callback() +{ + Assert(m_popup); +} + +CtrlPopup::~CtrlPopup() +{} + +void CtrlPopup::EmitAnswer(const AnswerCallbackData & answer) +{ + AnswerCallbackData l_answer = answer; + PopupAnswerEvent event(shared_from_this(), m_callback, l_answer); + DPL::Event::EventSupport::EmitEvent(event); +} + +PopupController::PopupController() : m_canvas(NULL) +{} + +CtrlPopupPtr PopupController::CreatePopup() const +{ + return CtrlPopupPtr( + new CtrlPopup(PopupManagerSingleton::Instance().CreatePopup())); +} + +void PopupController::OnEventReceived(const ShowPopupEventShort& event) +{ + CtrlPopupPtr popup = event.GetArg0(); + popup->m_callback = event.GetArg1(); + + //pass canvas from controller to manager + //canvas is not passed earlier because value wasn't set properly + PopupManagerSingleton::Instance().setExternalCanvas(getExternalCanvas()); + + PopupManagerSingleton::Instance().RunAsyncWithArgType( + popup->m_popup, + &PopupController::StaticOnAnswerReceived, + new CtrlPopupPtr(popup)); +} + +void PopupController::StaticOnAnswerReceived(const AnswerCallbackData & answer, + CtrlPopupPtr* popup) +{ + Assert(popup != NULL); + (*popup)->EmitAnswer(answer); + delete popup; // Just SharedPtr is destroyed, not the popup itself +} + +void PopupControllerUser::OnEventReceived(const PopupAnswerEvent& event) +{ + //Here we are in a proper context to call the callback + PopupAnswerCallback answerCall = event.GetArg1(); + AnswerCallbackData answer = event.GetArg2(); + answerCall.Call(answer); + event.GetArg0()->DPL::Event::EventSupport::RemoveListener( + this); +} + +void PopupControllerUser::ListenForAnswer(CtrlPopupPtr popup) +{ + popup->DPL::Event::EventSupport::AddListener(this); +} +} +} //namespace Popup +} //namespace Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.h b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.h new file mode 100644 index 0000000..066fd2d --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_controller.h @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file popup_controller.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @bref Header file for popup controller + */ + +/** + * To display a popup from a given class: + * + * class ABC + * { + * void AskUser() + * { + * } + * + * void DoSomeLogicWithAnswer() + * { + * } + * }; + * + * ... update the class to something simmilar: + * + * class ABC : Popup::PopupControllerUser + * { + * void AskUser() { + * using namespace Popup; + * CtrlPopupPtr popup = + * PopupControllerSingletion::Instance().CreatePopup(); + * popup->SetTitle("Title"); + * popup->SetContent("Content"); + * popup->AddButton("name1", 1); + * popup->AddButton("name2", 2); + * ListenForAnswer(popup); + * ShowPopupEvent event(popup, + * MakeAnswerCallback(this, + * &ABC::DoSomeLogicWithAnswer)); + * CONTROLLER_POST_EVENT(PopupController, event); + * } + * + * void DoSomeLogicWithAnswer(Popup::LabelId answer) { + * if (answer == 1) + * ;//name1 pressed + * else if (answer == 2) + * ;//name2 pressed + * } + * }; + **/ + +#ifndef WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ +#define WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "popup_manager.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +typedef int LabelId; + +struct PopupAnswerCallback +{ + typedef void (PopupAnswerCallback::*MemberPtr)(); + + void* callee; + MemberPtr member; + void (*callTranslator)(PopupAnswerCallback* callData, + const AnswerCallbackData& answer); + + void Call(const AnswerCallbackData& answer) + { + callTranslator(this, answer); + } +}; + +class PopupController; +class CtrlPopup; + +typedef std::shared_ptr CtrlPopupPtr; + +DECLARE_GENERIC_EVENT_3(PopupAnswerEvent, + CtrlPopupPtr, + PopupAnswerCallback, + AnswerCallbackData) + +DECLARE_GENERIC_EVENT_2(ShowPopupEventShort, + CtrlPopupPtr, + PopupAnswerCallback) + +class CtrlPopup : public DPL::Event::EventSupport, + public std::enable_shared_from_this +{ + public: + void SetTitle(const std::string &title); + void Append(PopupObject::IPopupObject *object); + + ~CtrlPopup(); + + private: + friend class PopupController; + friend class std::shared_ptr; + + explicit CtrlPopup(IPopupPtr popup); + void EmitAnswer(const AnswerCallbackData& answer); + + IPopupPtr m_popup; + PopupAnswerCallback m_callback; +}; + +class PopupController : + public DPL::Event::Controller::Type> +{ + public: + CtrlPopupPtr CreatePopup() const; + + void setExternalCanvas(void* canvas) + { + m_canvas = canvas; + } + void* getExternalCanvas() const + { + return m_canvas; + } + void* m_canvas; + + protected: + virtual void OnEventReceived(const ShowPopupEventShort& event); + PopupController(); + + private: + static void StaticOnAnswerReceived(const AnswerCallbackData& answer, + CtrlPopupPtr* popup); +}; + +class PopupControllerUser : DPL::Event::EventListener +{ + template + struct PopupAnswerCallbackCreator + { + typedef void (Type::*MemberPtr)(const AnswerCallbackData& answer); + union Caster + { + MemberPtr specific; + PopupAnswerCallback::MemberPtr generic; + }; + + static PopupAnswerCallback Create(Type* callee, + MemberPtr callback) + { + PopupAnswerCallback callData; + + callData.callee = callee; + + Caster caster; + caster.specific = callback; + callData.member = caster.generic; + + callData.callTranslator = + &PopupAnswerCallbackCreator::MemberCallbackTranslator; + + return callData; + } + + static void MemberCallbackTranslator(PopupAnswerCallback* callData, + const AnswerCallbackData& answer) + { + Type* typedThis = static_cast(callData->callee); + Caster caster; + caster.generic = callData->member; + MemberPtr typedCallback = caster.specific; + (typedThis->*typedCallback)(answer); + } + }; + + protected: + virtual void OnEventReceived(const PopupAnswerEvent& event); + void ListenForAnswer(CtrlPopupPtr popup); + + template + PopupAnswerCallback MakeAnswerCallback(Type* This, + void (Type::*callback) + (const AnswerCallbackData &)) + { + return PopupAnswerCallbackCreator::Create(This, callback); + } +}; + +typedef DPL::Singleton PopupControllerSingleton; +} +} //namespace Popup +} //namespace Wrt + +#endif //WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp new file mode 100644 index 0000000..040f445 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_manager.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup_manager implementation file + */ + +#include "popup_manager.h" +#include +#include +#include +#include +#include "popup.h" + +IMPLEMENT_SINGLETON(Wrt::Popup::Renderer::PopupManager) + +namespace Wrt { +namespace Popup { +namespace Renderer { +void PopupManager::Initialize(PopupRendererPtr renderer) +{ + Assert(!m_initialized); + m_popupRenderer = renderer; + m_popupRenderer->Initialize(); + m_initialized = true; +} + +void PopupManager::Deinitialize() +{ + m_popupRenderer->Deinitialize(); + Assert(m_initialized); + m_popupRenderer.reset(); + m_initialized = false; +} + +IPopupPtr PopupManager::CreatePopup() +{ + Assert(m_initialized); + return m_popupRenderer->CreatePopup(); +} +} +} // namespace Popup +} // namespace Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.h b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.h new file mode 100644 index 0000000..40867bf --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_manager.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_manager.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup_manager declaration file + */ + +#ifndef WRT_SRC_POPUP_POPUP_MANAGER_H_ +#define WRT_SRC_POPUP_POPUP_MANAGER_H_ + +#include +#include +#include +#include +#include +#include "popup.h" +#include "popup_renderer.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +class PopupManager : DPL::Noncopyable +{ + template + struct TemplatedPopupCallback + { + typedef void (*Type)(const AnswerCallbackData& answer, ArgType* data); + }; + + public: + PopupManager() : m_initialized(false) {} + ~PopupManager() + { + if (m_initialized) { + LogError("Destroyed without Deinitialize"); + } + } + void Initialize (PopupRendererPtr creator); + void Deinitialize(); + void SetPopupRenderer (PopupRendererPtr creator); + IPopupPtr CreatePopup(); + + template + void RunAsyncWithArgType( + IPopupPtr popup, + typename TemplatedPopupCallback::Type + callback, + ArgType* argument) + { + Assert(callback); + WrapCbAndArg* wrapped = + new WrapCbAndArg(callback, argument); + popup->Show(&CallbackArgTypeTranslator, wrapped); + } + + void Show(IPopupPtr popup, + IPopup::PopupCallbackType callback, + void* userdata) + { + popup->Show(callback, userdata); + } + + void setExternalCanvas(void* externalCanvas) + { + AssertMsg(m_initialized, "Manger should be initialized"); + m_popupRenderer->setExternalCanvas(externalCanvas); + } + + private: + template + struct WrapCbAndArg + { + WrapCbAndArg(typename TemplatedPopupCallback::Type cb, + ArgType* arg) : + callback(cb), + argument(arg) + {} + + typename TemplatedPopupCallback::Type callback; + ArgType* argument; + }; + + template + static void CallbackArgTypeTranslator(const AnswerCallbackData & answer, + void* data) + { + WrapCbAndArg* wrapped = + static_cast< WrapCbAndArg* >(data); + wrapped->callback(answer, wrapped->argument); + delete wrapped; + } + + bool m_initialized; + PopupRendererPtr m_popupRenderer; +}; + +typedef DPL::Singleton PopupManagerSingleton; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_MANAGER_H_ diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_object.h b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_object.h new file mode 100644 index 0000000..86f7484 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_object.h @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_object.h + * @author Justyna Mejzner (j.mejzner@samsung.com) + * @version 1.0 + * @brief This is declaration file of PopupObject + */ + +#ifndef WRT_SRC_POPUP_POPUPOBJECT_H_ +#define WRT_SRC_POPUP_POPUPOBJECT_H_ + +#include + +#include +#include + +namespace Wrt { +namespace Popup { +namespace Renderer { +namespace PopupObject { +class IPopupObject; +class PopupObjectBase; +class Button; +class Label; +class Check; + +typedef std::list PopupObjects; + +enum PopupType +{ + BUTTON, + LABEL, + CHECK +}; + +class IPopupObject +{ + public: + virtual Button* asButton() = 0; + virtual Label* asLabel() = 0; + virtual Check* asCheck() = 0; + virtual PopupType getType() const = 0; + virtual ~IPopupObject() + {} +}; + +class PopupObjectBase : public IPopupObject +{ + public: + virtual Button* asButton() + { + Assert("wrong type"); + return NULL; + } + virtual Label* asLabel() + { + Assert("wrong type"); + return NULL; + } + virtual Check* asCheck() + { + Assert("wrong type"); + return NULL; + } + + PopupType getType() const + { + return m_type; + } + + protected: + PopupObjectBase(PopupType type) : m_type(type) + {} + + PopupType m_type; +}; + +class Button : public PopupObjectBase +{ + public: + Button(const std::string& label, + int labelId) : + PopupObjectBase(BUTTON), + m_label(label), + m_labelId(labelId) + {} + + Button* asButton() + { + return this; + } + + const std::string& getLabel() const + { + return m_label; + } + + int getLabelId() const + { + return m_labelId; + } + + private: + std::string m_label; + int m_labelId; +}; + +class Label : public PopupObjectBase +{ + public: + Label(const std::string &label) : + PopupObjectBase(LABEL), + m_label(label) + {} + + Label* asLabel() + { + return this; + } + + const std::string& getLabel() const + { + return m_label; + } + + private: + std::string m_label; +}; + +class Check : public PopupObjectBase +{ + public: + Check(const std::string &label) : + PopupObjectBase(CHECK), + m_checkLabel(label) + {} + + Check* asCheck() + { + return this; + } + + const std::string& getCheckLabel() const + { + return m_checkLabel; + } + + private: + std::string m_checkLabel; +}; +} /*PopupObject*/ +} +} //namespace Popup +} //namespace Wrt + +#endif //WRT_SRC_POPUP_POPUPOBJECT_H_ diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp new file mode 100644 index 0000000..6499dcc --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_renderer.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is efl specific implementation for PopupRenderer + */ + +#include "popup_renderer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "popup_manager.h" +#include "popup_manager.h" +#include "evas_object.h" + +namespace Wrt { +namespace { +using namespace Popup; +const char* EDJ_NAME = "/usr/share/edje/ace/generic_popup.edj"; +const char* POPUP_LAYOUT1 = "popup_layout1"; +const char* POPUP_LAYOUT2 = "popup_layout2"; +const char* POPUP_PART_TITLE = "title,text"; +const char* POPUP_PART_BUTTON1 = "button1"; +const char* POPUP_PART_BUTTON2 = "button2"; +const char* POPUP_PART_BUTTON3 = "button3"; +const char* BUTTON_CLICKED_CALLBACK_NAME = "clicked"; +const char* CHANGED_CALLBACK_NAME = "changed"; +const unsigned int MAX_NUMBER_OF_VERTICAL = 2; + +Evas_Object* create_layout_main(Evas_Object* parent, int totalV) +{ + Evas_Object *layout = elm_layout_add(parent); + + if (totalV == 1) { + elm_layout_file_set(layout, EDJ_NAME, POPUP_LAYOUT1); + } else if (totalV == 2) { + elm_layout_file_set(layout, EDJ_NAME, POPUP_LAYOUT2); + } else { + Assert(!"popup needs define new group in the edc"); + } + + evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + return layout; +} +} //namespace + +namespace Popup { +namespace Renderer { +class PopupRenderer::Impl +{ + public: + Impl() : + m_popupsToRender(), + m_current(), + m_initialized(false), + m_checkState(false), + m_themeIndexV(0), + m_externalCanvas(NULL) + {} + + ~Impl() + { + if (m_initialized) { + LogError("Destroyed without Deinitialize"); + } + } + + void Initialize() + { + Assert(!m_initialized); + m_initialized = true; + } + + void Deinitialize() + { + Assert(m_initialized); + m_current.reset(); + while (!m_popupsToRender.empty()) { + m_popupsToRender.pop(); + } + m_initialized = false; + } + + void ButtonCallback(EvasObject::IConnection* /*connection*/, + void* /*event_info*/, + void* data) + { + LogDebug("ButtonCallback"); + Assert(m_initialized); + AnswerCallbackData answerData; + + answerData.buttonAnswer = reinterpret_cast(data); + answerData.chackState = m_checkState; + answerData.password = m_password; + m_current->ForwardAnswer(answerData); + m_current.reset(); + + FOREACH(it, m_createdObjects) + { + if (it->IsValid()) { + evas_object_del(*it); + } + } + m_createdObjects.clear(); + m_checkState = false; + DoRender(); + } + + void CheckCallback(EvasObject::IConnection* connection, + void* /*event_info*/, + void* /* unused */) + { + m_checkState = + elm_check_state_get(connection->GetEvasObject()); + } + + void Render (PopupPtr popup) + { + Assert(m_initialized); + m_popupsToRender.push(popup); + DoRender(); + } + + void DoRender(const PopupObject::Label& object, + EvasObject& parent, + EvasObject& layout, + int themeIndex) + { + EvasObject label(elm_label_add(parent)); + + elm_object_style_set(label, "popup_description/default"); + elm_label_line_wrap_set(label, ELM_WRAP_WORD); + elm_object_text_set(label, object.getLabel().c_str()); + evas_object_size_hint_weight_set(label, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(label, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(label); + + elm_object_part_content_set( + layout, + DPL::lexical_cast(themeIndex).c_str(), + label); + m_createdObjects.push_back(label); + } + + void DoRender(const PopupObject::Check& object, + EvasObject& parent, + EvasObject& layout, + int themeIndex) + { + EvasObject check(elm_check_add(parent)); + + evas_object_size_hint_align_set(check, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_size_hint_weight_set(check, EVAS_HINT_EXPAND, 0.0); + elm_object_text_set(check, + object.getCheckLabel().c_str()); + elm_object_part_content_set( + layout, + DPL::lexical_cast(themeIndex).c_str(), + check); + + check.ConnectMemberSmartCallback(CHANGED_CALLBACK_NAME, + &Impl::CheckCallback, + this, + static_cast(NULL)); + evas_object_show(check); + m_createdObjects.push_back(check); + } + + void DoRender(const PopupObject::Button& object, + EvasObject &parent) + { + EvasObject btn(elm_button_add(parent)); + + elm_object_style_set(btn, "popup"); + elm_object_text_set(btn, object.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON1, btn); + btn.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast(object. + getLabelId())); + m_createdObjects.push_back(btn); + } + + void DoRender(const PopupObject::Button& object1, + const PopupObject::Button& object2, + EvasObject &parent) + { + DoRender(object1, parent); + + EvasObject btn2(elm_button_add(parent)); + + elm_object_style_set(btn2, "popup"); + elm_object_text_set(btn2, object2.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON2, btn2); + btn2.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast(object2. + getLabelId())); + m_createdObjects.push_back(btn2); + } + + void DoRender(const PopupObject::Button& object1, + const PopupObject::Button& object2, + const PopupObject::Button& object3, + EvasObject &parent) + { + DoRender(object1, object2, parent); + + EvasObject btn3(elm_button_add(parent)); + + elm_object_style_set(btn3, "popup"); + elm_object_text_set(btn3, object3.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON3, btn3); + btn3.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast(object3. + getLabelId())); + m_createdObjects.push_back(btn3); + } + + EvasObject getBaseObject() + { + if (getExternalCanvas() == NULL) { + LogDebug("Create old style popup"); + EvasObject win(elm_win_add(NULL, "Popup", ELM_WIN_DIALOG_BASIC)); + elm_win_borderless_set(win, EINA_TRUE); + elm_win_alpha_set(win, EINA_TRUE); + elm_win_raise(win); + { + int w, h, x, y; + ecore_x_window_geometry_get(ecore_x_window_root_first_get(), + &x, + &y, + &w, + &h); + evas_object_resize(win, w, h); + evas_object_move(win, x, y); + } + m_createdObjects.push_back(win); + evas_object_show(win); + return win; + } else { + LogDebug("Create new style popup"); + EvasObject win(getExternalCanvas()); + evas_object_show(win); + return win; + } + } + + void DoRender() + { + if (!m_current && !m_popupsToRender.empty()) { + m_current = m_popupsToRender.front(); + m_popupsToRender.pop(); + + m_themeIndexV = 0; + + // preprocessing + std::vector countPopupObjects = { 0 /* PopupObject::BUTTON */, + 0 /* PopupObject::LABEL */, + 0 /* PopupObject::CHECK */ }; + FOREACH(it, m_current->GetPopupObjects()) { + AssertMsg((*it)->getType() < countPopupObjects.size(), + "Wrong PopupObject assigned"); + countPopupObjects[(*it)->getType()]++; + } + int needsIndexV = countPopupObjects[PopupObject::LABEL] + + countPopupObjects[PopupObject::CHECK]; + + EvasObject win = getBaseObject(); + EvasObject main(elm_popup_add(win)); + + evas_object_size_hint_weight_set(main, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + elm_object_part_text_set(main, + POPUP_PART_TITLE, + m_current->GetTitle().c_str()); + + m_createdObjects.push_back(main); + std::vector buttonObjectList; + EvasObject layout(create_layout_main(main, needsIndexV)); + m_createdObjects.push_back(layout); + + FOREACH(it, m_current->GetPopupObjects()) { + switch ((*it)->getType()) { + case PopupObject::BUTTON: + buttonObjectList.push_back(*(*it)->asButton()); + break; + case PopupObject::LABEL: + DoRender(*(*it)->asLabel(), + main, + layout, + m_themeIndexV++); + break; + case PopupObject::CHECK: + DoRender(*(*it)->asCheck(), + main, + layout, + m_themeIndexV++); + break; + default: + Assert(!"incorrect type"); + } + Assert(m_themeIndexV <= MAX_NUMBER_OF_VERTICAL); + } + elm_object_content_set(main, + layout); + + // show buution + switch (buttonObjectList.size()) { + case 0: + LogDebug("no button"); + break; + case 1: + DoRender(buttonObjectList.at(0), + main); + break; + case 2: + DoRender(buttonObjectList.at(0), + buttonObjectList.at(1), + main); + break; + case 3: + DoRender(buttonObjectList.at(0), + buttonObjectList.at(1), + buttonObjectList.at(2), + main); + break; + default: + Assert(!"incorrect button number"); + break; + } + + evas_object_show(main); + } + } + + void setExternalCanvas(void* externalCanvas) + { + m_externalCanvas = static_cast(externalCanvas); + } + + Evas_Object* getExternalCanvas() const + { + return m_externalCanvas; + } + + std::queue m_popupsToRender; + std::list m_createdObjects; + PopupPtr m_current; + bool m_initialized; + bool m_checkState; + DPL::OptionalStdString m_password; + unsigned int m_themeIndexV; + + private: + Evas_Object* m_externalCanvas; +}; + +PopupRenderer::PopupRenderer() +{ + m_impl = new PopupRenderer::Impl(); +} + +PopupRenderer::~PopupRenderer() +{ + delete m_impl; +} + +void PopupRenderer::Initialize() +{ + Assert(m_impl); + m_impl->Initialize(); +} + +void PopupRenderer::Deinitialize() +{ + Assert(m_impl); + m_impl->Deinitialize(); +} + +IPopupPtr PopupRenderer::CreatePopup() +{ + return std::static_pointer_cast(IPopupPtr + (new Popup(shared_from_this()))); +} + +void PopupRenderer::Render(PopupPtr popup) +{ + m_impl->Render(popup); +} + +void PopupRenderer::setExternalCanvas(void* externalCanvas) +{ + m_impl->setExternalCanvas(externalCanvas); +} +} +} // namespace Popup +} // namespace Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h new file mode 100644 index 0000000..3538bbb --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file popup_renderer.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is declaration file of PopupRenderer + */ + +#ifndef WRT_SRC_POPUP_POPUP_RENDERER_H_ +#define WRT_SRC_POPUP_POPUP_RENDERER_H_ + +#include +#include +#include + +#include +#include +#include +#include +#include "popup.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +class PopupRenderer : public std::enable_shared_from_this +{ + public: + PopupRenderer(); + ~PopupRenderer(); + void Initialize(); + void Deinitialize(); + IPopupPtr CreatePopup(); + virtual void setExternalCanvas(void* externalCanvas); + + protected: + class Popup; + typedef std::shared_ptr PopupPtr; + + class Popup : public IPopup + { + public: + typedef std::map ButtonMap; + virtual void SetTitle(const std::string &title) + { + LogDebug(title); + Assert(m_title.empty()); + m_title = title; + } + + virtual void Append(PopupObject::IPopupObject *object) + { + m_popupObjectList.push_back(object); + } + + virtual void Show(IPopup::PopupCallbackType callback, + void* data) + { + Assert(callback); + m_data = data; + m_callback = callback; + m_renderer->Render(std::static_pointer_cast(shared_from_this())); + } + + const std::string& GetTitle() const + { + return m_title; + } + + PopupObject::PopupObjects& GetPopupObjects() + { + return m_popupObjectList; + } + + virtual ~Popup() + { + FOREACH(it, m_popupObjectList) { + delete *it; + } + } + + private: + friend class PopupRenderer; + friend class std::shared_ptr; + friend class PopupObjectTheme; + + Popup(std::shared_ptr renderer) : m_renderer(renderer) + {} + + void ForwardAnswer(const AnswerCallbackData & answer) const + { + m_callback(answer, m_data); + } + + std::string m_title; + void* m_data; + IPopup::PopupCallbackType m_callback; + PopupObject::PopupObjects m_popupObjectList; + std::shared_ptr m_renderer; + }; + + private: + void Render (PopupPtr popup); + + class Impl; + Impl* m_impl; +}; + +typedef std::shared_ptr PopupRendererPtr; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_RENDERER_H_ diff --git a/src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.cpp b/src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.cpp new file mode 100644 index 0000000..41d683d --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "wrt-popup.h" +#include +#include + +#include +#include +#include +#include + +#include "PopupEnum.h" +#include "PopupSerializer.h" +#include "YesNoPopup.h" +#include "InfoPopup.h" +#include "YesNoCheckPopup.h" + +namespace Wrt { +namespace Popup { +bool WrtPopup::openPipes() +{ + Try + { + if (m_argc != 3) { + LogError("Wrong arguments!"); + return false; + } + m_input.Open(m_argv[1]); + //open output pipe + m_output.Open(m_argv[2]); + + DPL::WaitableHandleWatchSupport::InheritedContext()-> + AddWaitableHandleWatch(this, + m_input.WaitableReadHandle(), + DPL::WaitMode::Read); + m_pipesOpened = true; + return true; + } + Catch(DPL::Exception) + { + LogError("cannot open pipes"); + } + return false; +} + +void WrtPopup::closePipes() +{ + Try + { + if (m_pipesOpened) { + DPL::WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, + m_input.WaitableReadHandle(), + DPL::WaitMode::Read); + m_input.Close(); + m_output.Close(); + m_pipesOpened = false; + } + } + Catch(DPL::Exception) + { + LogError("cannot close pipes"); + } +} + +void WrtPopup::OnEventReceived(const QuitEvent & /* event */) +{ + LogDebug("Quiting"); + closePipes(); + Quit(); +} + +void WrtPopup::OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type /*mode*/) +{ + if (waitableHandle == m_input.WaitableReadHandle()) { + readInputData(); + } +} + +void WrtPopup::readInputData() +{ + DPL::BinaryQueueAutoPtr data = + m_input.Read(std::numeric_limits::max()); + int popupType = PopupSerializer::getIntArg(*data); + LogDebug("popup type " << popupType); + switch (popupType) { + case YES_NO_PROMPT: + m_popup.reset(new YesNoPopup()); + m_popup->show(data, this); + break; + case INFO_PROMPT: + m_popup.reset(new InfoPopup()); + m_popup->show(data, this); + break; + case YES_NO_CHECK_PROMPT: + m_popup.reset(new YesNoCheckPopup()); + m_popup->show(data, this); + break; + default: + Assert(false); + } +} + +void WrtPopup::response(DPL::BinaryQueue result) +{ + m_output.Write(result, result.Size()); + PostEvent(QuitEvent()); +} + +void WrtPopup::OnStop() +{ + LogDebug("On Stop"); +} + +void WrtPopup::OnCreate() +{ + if (!openPipes()) { + PostEvent(QuitEvent()); + } + LogDebug("On Create"); +} + +void WrtPopup::OnResume() +{ + LogDebug("OnResume"); +} + +void WrtPopup::OnPause() +{ + LogDebug("OnPause"); +} + +void WrtPopup::OnReset(bundle */*b*/) +{ + LogDebug("OnReset"); +} + +void WrtPopup::OnTerminate() +{ + LogDebug("Wrt Shutdown now"); +} + +WrtPopup::WrtPopup(int argc, char **argv) : + Application(argc, argv, "wrt-popup", false), + m_pipesOpened(false) +{ + Touch(); + Renderer::PopupControllerSingleton::Instance().Touch(); + Renderer::PopupManagerSingleton::Instance().Initialize( + Renderer::PopupRendererPtr(new Renderer::PopupRenderer)); + LogDebug("App Created"); +} + +WrtPopup::~WrtPopup() +{ + Renderer::PopupManagerSingleton::Instance().Deinitialize(); + LogDebug("App Finished"); +} +} +} + +int main(int argc, char *argv[]) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // Output on stdout will be flushed after every newline character, + // even if it is redirected to a pipe. This is useful for running + // from a script and parsing output. + // (Standard behavior of stdlib is to use full buffering when + // redirected to a pipe, which means even after an end of line + // the output may not be flushed). + setlinebuf(stdout); + + DPL::Log::LogSystemSingleton::Instance().SetTag("WRT-POPUP"); + Wrt::Popup::WrtPopup app(argc, argv); + int ret = app.Exec(); + LogDebug("App returned: " << ret); + return ret; + } + UNHANDLED_EXCEPTION_HANDLER_END +} diff --git a/src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.h b/src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.h new file mode 100644 index 0000000..ab9c519 --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-bin/wrt-popup.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_H +#define WRT_POPUP_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "popup_controller.h" + +namespace Wrt { +namespace Popup { +DECLARE_GENERIC_EVENT_0(QuitEvent) +class WrtPopup; + +class IPopup : public Renderer::PopupControllerUser +{ + public: + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) = 0; + virtual ~IPopup() {} +}; + +typedef std::unique_ptr IPopupPtr; + +class WrtPopup : + public DPL::WaitableHandleWatchSupport::WaitableHandleListener, + public DPL::Application, + private DPL::Event::Controller::Type> +{ + public: + WrtPopup(int argc, char **argv); + virtual ~WrtPopup(); + + void response(DPL::BinaryQueue result); + + protected: + //DPL::Application functions + virtual void OnStop(); + virtual void OnCreate(); + virtual void OnResume(); + virtual void OnPause(); + virtual void OnReset(bundle *b); + virtual void OnTerminate(); + virtual void OnEventReceived(const QuitEvent &event); + virtual void OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type mode); + + private: + + void showAcePrompt(DPL::BinaryQueueAutoPtr data); + void communicationBoxResponse(int buttonAnswer, + bool checkState, + void* userdata); + bool m_pipesOpened; + IPopupPtr m_popup; + + bool openPipes(); + void closePipes(); + void readInputData(); + + DPL::NamedInputPipe m_input; + DPL::NamedOutputPipe m_output; +}; +} +} + +#endif // WRT_POPUP_H diff --git a/src_wearable/wrt-popup/wrt/popup-runner/CMakeLists.txt b/src_wearable/wrt-popup/wrt/popup-runner/CMakeLists.txt new file mode 100644 index 0000000..0a8f45e --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-runner/CMakeLists.txt @@ -0,0 +1,66 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_RUNNER_LIB_DEP + dpl-efl + REQUIRED +) + +set(WRT_POPUP_RUNNER_LIB_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/wrt/popup-runner) + +set(WRT_POPUP_RUNNER_LIB_SOURCES + ${WRT_POPUP_COMMON_SRCS} + ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/PopupInvoker.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_RUNNER_LIB_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_RUNNER_LIB_SRC_DIR} + ${WRT_POPUP_RUNNER_LIB_DEP_INCLUDE_DIRS} + ${WRT_POPUP_COMMON_DIR} +) + +ADD_LIBRARY(${TARGET_POPUP_WRT_RUNNER_LIB} SHARED + ${WRT_POPUP_RUNNER_LIB_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +target_link_libraries(${TARGET_POPUP_WRT_RUNNER_LIB} + ${WRT_POPUP_RUNNER_LIB_DEP_LIBRARIES} + ${WRT_POPUP_RUNNER_LIB_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_WRT_RUNNER_LIB} + DESTINATION lib +) + +INSTALL(FILES ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/PopupInvoker.h + DESTINATION ${DESTINATION_HEADERS_WRT_POPUP_RUNNER} +) diff --git a/src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.cpp b/src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.cpp new file mode 100644 index 0000000..16cbace --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "PopupInvoker.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "PopupEnum.h" +#include "PopupSerializer.h" + +namespace { +const char *POPUP_EXEC = "/usr/bin/wrt-popup-wrt-runtime"; +} + +namespace Wrt { +namespace Popup { +PopupInvoker::PopupInvoker() +{ + char tmp[L_tmpnam + 1]; + if (NULL == tmpnam(tmp)) + ThrowMsg(DPL::Exception, "Failed to get pipe name"); + m_inputName = tmp; + + if (NULL == tmpnam(tmp)) + ThrowMsg(DPL::Exception, "Failed to get pipe name"); + m_outputName = tmp; + + m_input.Create(m_inputName); + m_output.Create(m_outputName); + LogDebug("Pipes created"); +} + +PopupInvoker::~PopupInvoker() +{ + Try + { + m_input.Destroy(m_inputName); + m_output.Destroy(m_outputName); + LogDebug("Pipes destroyed"); + } + Catch(DPL::Exception) + { + LogError("Cannot destroy pipes"); + } +} + +bool PopupInvoker::askYesNo(const std::string& title, + const std::string& message) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(YES_NO_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + + //Result from popup application is available. Read it. + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits::max()); + const int success = PopupSerializer::getIntArg(*resultData); + bool retVal = false; + if (success) { + const int result = PopupSerializer::getIntArg(*resultData); + + LogDebug("Popup result is: " << result); + + Assert(resultData->Empty()); + retVal = (!!result); + } else { + LogWarning("Failed to show popup."); + } + + tmp.Close(); + m_input.Close(); + m_output.Close(); + + return retVal; + } + Catch(DPL::Exception) + { + LogError("error occured"); + } + + return false; +} + +void PopupInvoker::showInfo(const std::string& title, + const std::string& message, + const std::string& buttonLabel) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(INFO_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + PopupSerializer::appendArg(buttonLabel, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits::max()); + const int success = PopupSerializer::getIntArg(*resultData); + if (!success) { + LogWarning("Failed to show popup."); + } + //ignore result + + tmp.Close(); + m_input.Close(); + m_output.Close(); + } + Catch(DPL::Exception) + { + LogError("error occured"); + } +} + +PopupResponse PopupInvoker::askYesNoCheckbox(const std::string& title, + const std::string& message, + const std::string& checkboxLabel) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(YES_NO_CHECK_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + PopupSerializer::appendArg(checkboxLabel, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + + //Result from popup application is available. Read it. + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits::max()); + const int success = PopupSerializer::getIntArg(*resultData); + if (success) { + const int result = PopupSerializer::getIntArg(*resultData); + const int rememberResult = PopupSerializer::getIntArg(*resultData); + + LogDebug( + "Popup result is: " << result << " remeber: " << rememberResult); + + Assert(resultData->Empty()); + tmp.Close(); + m_input.Close(); + m_output.Close(); + + if (1 == result) { + if (rememberResult == 1) { + return YES_DO_REMEMBER; + } else { + return YES_DONT_REMEMBER; + } + } else { + if (rememberResult == 1) { + return NO_DO_REMEMBER; + } else { + return NO_DONT_REMEMBER; + } + } + } else { + LogWarning("Popup failed to execute."); + tmp.Close(); + m_input.Close(); + m_output.Close(); + return NO_DONT_REMEMBER; + } + } + Catch(DPL::Exception) + { + LogError("error occured"); + } + return NO_DONT_REMEMBER; +} + +void PopupInvoker::executePopup() +{ + pid_t pid = fork(); + if (pid == -1) { + //error occured + LogError("Failed to create popup process."); + Assert(false); + } + if (pid == 0) { + //child process + int ret = execl(POPUP_EXEC, + POPUP_EXEC, + m_outputName.c_str(), + m_inputName.c_str(), + NULL); + if (ret == -1) { + //execl returns -1 on error + LogError("Failed to set popup binary"); + //write something to pipe to unblock caller process + DPL::NamedOutputPipe errOut; + errOut.Open(m_inputName); + DPL::BinaryQueue data; + PopupSerializer::appendArg(false, data); + errOut.Write(data, data.Size()); + errOut.Close(); + + Assert(false); + } + } + + DPL::WaitableHandle handle = m_input.WaitableReadHandle(); + DPL::WaitForSingleHandle(handle); +} +} // Popup +} // Wrt diff --git a/src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.h b/src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.h new file mode 100644 index 0000000..278db6d --- /dev/null +++ b/src_wearable/wrt-popup/wrt/popup-runner/PopupInvoker.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WRT_POPUP_INVOKER_H +#define WRT_POPUP_INVOKER_H + +#include + +#include +#include + +/* + * + * Example usage: + * + * bool result = PopupInvoker().askYesNo("title", "message"); + * + */ + +namespace Wrt { +namespace Popup { +enum PopupResponse { + NO_DO_REMEMBER, + NO_DONT_REMEMBER, + YES_DONT_REMEMBER, + YES_DO_REMEMBER +}; + +class PopupInvoker +{ + public: + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, PopupInvokerException) + }; + + PopupInvoker(); + ~PopupInvoker(); + + bool askYesNo(const std::string &title, const std::string &message); + void showInfo(const std::string &title, + const std::string &message, + const std::string &buttonLabel = std::string("OK")); + PopupResponse askYesNoCheckbox(const std::string& title, + const std::string& message, + const std::string& checkboxLabel); + + private: + + void executePopup(); + + DPL::NamedInputPipe m_input; + DPL::NamedOutputPipe m_output; + std::string m_inputName; + std::string m_outputName; +}; +} // Popup +} // Wrt + +#endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..406edbd --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,21 @@ +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# + +INCLUDE(CMakeUtils.txt) + +ADD_SUBDIRECTORY(dao) diff --git a/tests/CMakeUtils.txt b/tests/CMakeUtils.txt new file mode 100644 index 0000000..cb27239 --- /dev/null +++ b/tests/CMakeUtils.txt @@ -0,0 +1,69 @@ +# @file CMakeUtils.txt +# @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) +# @author Pawel Sikorski (p.sikorski@samsung.com) +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Replacement functions for standard (w/o "WRT_" prefix) CMake functions. +# They store supplied arguments in global properties to assign them to tests. +FUNCTION(WRT_INCLUDE_DIRECTORIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_INCLUDE_DIRS ${ARGV}) +ENDFUNCTION(WRT_INCLUDE_DIRECTORIES) + +FUNCTION(WRT_LINK_DIRECTORIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_LIBRARY_DIRS ${ARGV}) +ENDFUNCTION(WRT_LINK_DIRECTORIES) + +FUNCTION(WRT_TARGET_LINK_LIBRARIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_LIBRARIES ${ARGV}) +ENDFUNCTION(WRT_TARGET_LINK_LIBRARIES) + +FUNCTION(WRT_TEST_LIBRARY) + SET_PROPERTY(GLOBAL APPEND PROPERTY COMMON_TESTS_LIBRARY ${ARGV}) +ENDFUNCTION(WRT_TEST_LIBRARY) + +# Functions used to build test targets (proper sources, includes, libs are +# added automatically) +FUNCTION(WRT_TEST_BUILD TARGET_NAME) + SET(SOURCES "${ARGN}") + ADD_EXECUTABLE("${TARGET_NAME}" + ${SOURCES} + ) + # get include dirs global property + GET_PROPERTY(INCLUDE_DIRS GLOBAL PROPERTY TESTS_INCLUDE_DIRS) + INCLUDE_DIRECTORIES( + ${INCLUDE_DIRS} + ) + # get library dirs global property + GET_PROPERTY(LIBRARY_DIRS GLOBAL PROPERTY TESTS_LIBRARY_DIRS) + LINK_DIRECTORIES( + ${LIBRARY_DIRS} + ) + # get link libraries global property + GET_PROPERTY(LINK_LIBRARIES GLOBAL PROPERTY TESTS_LIBRARIES) + GET_PROPERTY(TEST_LIBRARY GLOBAL PROPERTY COMMON_TESTS_LIBRARY) + TARGET_LINK_LIBRARIES("${TARGET_NAME}" + ${TEST_LIBRARY} + ${LINK_LIBRARIES} + ) +ENDFUNCTION(WRT_TEST_BUILD) + +FUNCTION(WRT_TEST_INSTALL) + SET_TARGET_PROPERTIES(${ARGV} PROPERTIES + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON + ) + INSTALL(TARGETS ${ARGV} + DESTINATION bin + PERMISSIONS OWNER_READ + OWNER_WRITE + OWNER_EXECUTE + GROUP_READ + GROUP_EXECUTE + WORLD_READ + WORLD_EXECUTE + ) +ENDFUNCTION(WRT_TEST_INSTALL) diff --git a/tests/dao/CMakeLists.txt b/tests/dao/CMakeLists.txt new file mode 100644 index 0000000..e970f44 --- /dev/null +++ b/tests/dao/CMakeLists.txt @@ -0,0 +1,47 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Andrzej Surdej (a.surdej@sasmung.com) +# @version 1.0 +# @brief +# + +SET(TARGET_WIDGETDB_TEST "wrt-plugins-common-tests-widgetdb") + +pkg_search_module(dpl REQUIRED dpl-efl) +pkg_search_module(dpl-test REQUIRED dpl-test-efl) + +include_directories( + ${dpl_INCLUDE_DIRS} + ${dpl-test_INCLUDE_DIRS} +) + +# Set widgetdb tests sources +SET(WIDGETDB_TESTS_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/TestInit.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/WidgetDBTest.cpp") + +WRT_TEST_BUILD(${TARGET_WIDGETDB_TEST} ${WIDGETDB_TESTS_SOURCES}) +WRT_TEST_INSTALL(${TARGET_WIDGETDB_TEST}) + +target_link_libraries(${TARGET_WIDGETDB_TEST} + "wrt-plugins-widgetdb" + ${dpl_LIBRARIES} + ${dpl-test_LIBRARIES} +) + +INSTALL(PROGRAMS + ${CMAKE_CURRENT_SOURCE_DIR}/widgetdb_tests_prepare_db.sh + DESTINATION bin + ) diff --git a/tests/dao/README b/tests/dao/README new file mode 100644 index 0000000..a618eb1 --- /dev/null +++ b/tests/dao/README @@ -0,0 +1,12 @@ +Plugins DAO +System tests. Tests widget's private database data access object. +Binary file: plugins-tests-widgetdb. Uses our test framework. Allows to use +different types of output. Text output shows results on console - green passed. +To run: +1. Install wrt-extra on target +2. Run plugins-tests-widgetdb --output=text + +Automatic: YES +Included in Daily Build: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-INT) +Included in Gerrit Builds: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-GERRIT) +Number of test cases: 22 \ No newline at end of file diff --git a/tests/dao/TestInit.cpp b/tests/dao/TestInit.cpp new file mode 100644 index 0000000..108a5c5 --- /dev/null +++ b/tests/dao/TestInit.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestInit.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Init widgetDB module test + */ + +#include +#include +#include +#include + +int main (int argc, char *argv[]) +{ + int ret = system("/usr/bin/widgetdb_tests_prepare_db.sh start"); + + if (!WIFEXITED(ret)) { //unexpected terminate + LogDebug("Fail while preparing database. Restoring"); + ret = system("/usr/bin/widgetdb_tests_prepare_db.sh stop"); + if (ret != 0) + LogError("Finalization script has return error: " << ret); + + return -1; + } else if (WEXITSTATUS(ret)) { //wrong script command, nothing done + LogError("Preparation script has return error: " << ret + << ". Quitting"); + return -1; + } + + LogDebug("Starting tests"); + + WrtDB::WrtDatabase::attachToThreadRW(); + + int status = + DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + + WrtDB::WrtDatabase::detachFromThread(); + + ret = system("/usr/bin/widgetdb_tests_prepare_db.sh stop"); + if (ret != 0) { + LogError("Finalization script has return error: " << ret); + return -1; + } + + return status; +} diff --git a/tests/dao/WidgetDBTest.cpp b/tests/dao/WidgetDBTest.cpp new file mode 100644 index 0000000..d8a5d50 --- /dev/null +++ b/tests/dao/WidgetDBTest.cpp @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file WidgetDBTest.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief This file contains tests for widgetDB commons module + */ + +#include +#include +#include +#include +#include +#include + +using namespace WrtDeviceApis::WidgetDB::Api; + +#define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ + do \ + { \ + std::string temp(in); \ + RUNNER_ASSERT_MSG(temp == (test), "Equals: [" << temp << "]"); \ + } \ + while (0) + +RUNNER_TEST_GROUP_INIT(WidgetDB) + +/* + * Name: widgetDB_test_get_language1 + * Description: check default widget language + * Expected: default should be "en" + */ +RUNNER_TEST(widgetDB_test_get_language1) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string lang = widget->getLanguage(); + + LogDebug("language is: " << lang); + RUNNER_ASSERT_WHAT_EQUALS(lang, "en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_language2 + * Description: check language returned by WidgetDB if widget does nto exists + * Expected: result should be "" + */ +RUNNER_TEST(widgetDB_test_get_language2) +{ + try { + IWidgetDBPtr widget = getWidgetDB(1000); //widget not exist + std::string lang = widget->getLanguage(); + + LogDebug("language is: " << lang); + RUNNER_ASSERT_WHAT_EQUALS(lang, ""); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_id + * Description: check GUID returned by WidgetDB + * Expected: GUID should match this, which was inserted into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_id) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::ID); + + LogDebug("id is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_id_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_version + * Description: check version returned by WidgetDB + * Expected: version should match this, which was inserted into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_version) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::VERSION); + + LogDebug("version is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "1.0.0"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_description + * Description: check description returned by WidgetDB + * Expected: description should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_description) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::DESCRIPTION); + + LogDebug("description is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_desc_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_license + * Description: check license returned by WidgetDB + * Expected: license should match this, which was inserted into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_license) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::LICENSE); + + LogDebug("licence is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_lic_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_license_href + * Description: check license href returned by WidgetDB + * Expected: license href should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_license_href) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::LICENSE_HREF); + + LogDebug("license href is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_lic_href_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_author_name + * Description: check author name href returned by WidgetDB + * Expected: author name should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_author_name) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::AUTHOR_NAME); + + LogDebug("author name is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "a_name_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_author_href + * Description: check author href returned by WidgetDB + * Expected: author href should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_author_href) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::AUTHOR_HREF); + + LogDebug("author href is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "a_href_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_author_email + * Description: check author email returned by WidgetDB + * Expected: author email should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_author_email) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::AUTHOR_EMAIL); + + LogDebug("author email is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "a_email_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_name + * Description: check localized widget name returned by WidgetDB + * Expected: localized widget name should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_name) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::NAME); + + LogDebug("name is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_name_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_short_name + * Description: check localized widget short name returned by WidgetDB + * Expected: localized widget short name should match this, which was inserted + * into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_short_name) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::SHORT_NAME); + + LogDebug("short name is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_shortname_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_width + * Description: check widget prefered width returned by WidgetDB + * Expected: widget prefered width should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_width) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::WIDTH); + + LogDebug("width is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "100"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_height + * Description: check widget prefered height returned by WidgetDB + * Expected: widget prefered height should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_height) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::HEIGHT); + + LogDebug("height is: " << tmp); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "200"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_paths + * Description: check widget installation path returned by WidgetDB + * Expected: widget installation path should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_paths) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::INSTALL_PATH); + + LogDebug("install path is: " << tmp); + + tmp = widget->getConfigValue( + ConfigAttribute::PUBLIC_STORAGE_PATH); + + LogDebug("public storage path is: " << tmp); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogDebug("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_empty + * Description: check if requesting GUID from WidgetDB throw excpetion if widget + * does not exists + * Expected: accessing GUID should throw + * WrtDeviceApis::Commons::SecurityException + */ +RUNNER_TEST(widgetDB_test_get_config_value_empty) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2005); + widget->getConfigValue(ConfigAttribute::ID); + + //exception should be thrown + RUNNER_ASSERT(false); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogDebug("OK. Exception thrown." << e.DumpToString()); + } +} + +/* + * Name: widgetDB_test_check_installation_status_installed + * Description: check if widget is installed by WidgetDB + * Expected: plugin should be notified that widget is installed + */ +RUNNER_TEST(widgetDB_test_check_installation_status_installed) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + InstallationStatus tmp = widget->checkInstallationStatus( + "w_id_2000", "w_name_2000_en", "2.0.0"); + + RUNNER_ASSERT(tmp == InstallationStatus::STATUS_INSTALLED); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_check_installation_status_uninstalled + * Description: check if widget is not installed by WidgetDB + * Expected: plugin should be notified that widget is not installed + */ +RUNNER_TEST(widgetDB_test_check_installation_status_uninstalled) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + InstallationStatus tmp = widget->checkInstallationStatus( + "w_id_2011", "w_name_2000_en", "2.0.0"); + + RUNNER_ASSERT(tmp == InstallationStatus::STATUS_UNINSTALLED); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_check_installation_status_latest + * Description: check if widget installation information is taken from latest + * version + * Expected: plugin installation status should be same is both calls of WidgetDB + */ +RUNNER_TEST(widgetDB_test_check_installation_status_latest) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + InstallationStatus tmp1 = widget->checkInstallationStatus( + "w_id_2000", "w_name_2000_en", "0.1.0"); + InstallationStatus tmp2 = widget->checkInstallationStatus( + "w_id_2000", "w_name_2000_en", "1.0.0"); + + RUNNER_ASSERT(tmp1 == InstallationStatus::STATUS_LATEST); + RUNNER_ASSERT(tmp2 == InstallationStatus::STATUS_LATEST); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + LogError("Exception thrown." << e.DumpToString()); + RUNNER_ASSERT(false); + } +} + +#undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/widgetdb_tests_prepare_db.sh b/tests/dao/widgetdb_tests_prepare_db.sh new file mode 100755 index 0000000..fce6486 --- /dev/null +++ b/tests/dao/widgetdb_tests_prepare_db.sh @@ -0,0 +1,122 @@ +#!/bin/sh +# +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# + +WRT_DB=/opt/dbspace/.wrt.db +WRT_DB_BCK=/tmp/wrt.db_backup + +if [ "x$1" == "xstart" ]; then + echo start; + cp $WRT_DB $WRT_DB_BCK + wrt_commons_create_clean_db.sh; + + #simple plugins + INS_MIN_PLUGINPROP="insert into PluginProperties(PluginPropertiesId, InstallationState, PluginLibraryName" + INS_ALL_PLUGINPROP="insert into PluginProperties(PluginPropertiesId, InstallationState, PluginLibraryName, PluginLibraryPath)" + + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}) VALUES(1, 1, 'plugin1')"; + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}, PluginLibraryPath) VALUES(2, 1, 'plugin2', 'path_to_plugin2')"; + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}) VALUES(3, 1, 'plugin3')"; + sqlite3 $WRT_DB "${INS_ALL_PLUGINPROP} VALUES(4, 1, 'p4', 'path_to_p4')"; + sqlite3 $WRT_DB "${INS_ALL_PLUGINPROP} VALUES(5, 1, 'p5', 'path_to_p5')"; + + #simple features + INS_ALL_FEATURESLIST="insert into FeaturesList(FeatureUUID, FeatureName, PluginPropertiesId)" + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(1, 'feature1', 1)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(2, 'feature2', 4)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(3, 'feature3', 4)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(4, 'feature4', 4)"; + + #Device capab + #TODO + + #Widgets + INS_ALL_WIDGETEXT="insert into WidgetExtendedInfo(app_id)" + INS_ALL_WIDGET="insert into WidgetInfo(app_id, widget_id, widget_version, widget_width, widget_height, author_name, author_email, author_href, base_folder, webkit_plugins_required, wac_signed, min_version, back_supported, access_network, defaultlocale, tizen_appid)" + INS_ALL_WIDGET_LOC="insert into LocalizedWidgetInfo(app_id, widget_locale, widget_name, widget_shortname, widget_description, widget_license, widget_license_file, widget_license_href)" + INS_ALL_WIDGET_ICONS="insert into WidgetIcon(app_id, icon_src, icon_width, icon_height)" + INS_ALL_WIDGET_LOC_ICONS="insert into WidgetLocalizedIcon(app_id, icon_id, widget_locale)" + INS_ALL_WIDGET_STARTFILE="insert into WidgetStartFile(app_id, src)" + INS_ALL_WIDGET_LOC_STARTFILE="insert into WidgetLocalizedStartFile(app_id, start_file_id, widget_locale, type, encoding)" + INS_ALL_WIDGET_DEFPREF="insert into WidgetDefaultPreference(app_id, key_name, key_value, readonly)" + INS_ALL_WIDGET_PREF="insert into WidgetPreference(app_id, tizen_appid, key_name, key_value, readonly)" + INS_ALL_WIDGET_FEATURE="insert into WidgetFeature(widget_feature_id, app_id, name, rejected)" + INS_ALL_WIDGET_WINMODES="insert into WidgetWindowModes(app_id, window_mode)" + INS_ALL_WIDGET_WARP="insert into WidgetWARPInfo(app_id, iri, subdomain_access)" + INS_ALL_WIDGET_CERT="insert into WidgetCertificateFingerprint(app_id, owner, chainid, type, md5_fingerprint, sha1_fingerprint, common_name)" + INS_ALL_WIDGET_POWDERLEV="insert into PowderLevels(app_id, category, level)" + INS_ALL_WIDGET_POWDERLEV_CONT="insert into PowderLevelContexts(levelid, context)" + + + sqlite3 $WRT_DB "${INS_ALL_WIDGET} VALUES(2000, 'w_id_2000', '1.0.0', 100, 200, 'a_name_2000', 'a_email_2000', 'a_href_2000', 'basef_2000', 1, 1, '1.0', 0, 0, 'en', 'tid2000')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET} VALUES(2001, 'w_id_2001', '2.0.0', 100, 200, 'a_name_2001', 'a_email_2001', 'a_href_2001', 'basef_2001', 1, 1, '0.5', 0, 0, 'en', 'tid2001')"; + sqlite3 $WRT_DB "insert into WidgetInfo(app_id, back_supported, tizen_appid) VALUES(2002, 0, 'tid2002')"; + sqlite3 $WRT_DB "insert into WidgetInfo(app_id, back_supported, tizen_appid) VALUES(2003, 0, 'NOTUSEDPKGNAME3')"; # for properties tests + + sqlite3 $WRT_DB "${INS_ALL_WIDGETEXT} VALUES(2000)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGETEXT} VALUES(2001)"; + sqlite3 $WRT_DB "insert into WidgetExtendedInfo(app_id) VALUES(2002)"; + sqlite3 $WRT_DB "insert into WidgetExtendedInfo(app_id) VALUES(2003)"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC} VALUES(2000, 'en', 'w_name_2000_en', 'w_shortname_2000_en', 'w_desc_2000_en', 'w_lic_2000_en', 'w_licf_2000_en', 'w_lic_href_2000_en')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC} VALUES(2000, 'pl', 'w_name_2000_pl', 'w_shortname_2000_pl', 'w_desc_2000_pl', 'w_lic_2000_pl', 'w_licf_2000_pl', 'w_lic_href_2000_pl')"; + sqlite3 $WRT_DB "insert into LocalizedWidgetInfo(app_id, widget_locale) VALUES(2002, 'en')"; + sqlite3 $WRT_DB "insert into LocalizedWidgetInfo(app_id, widget_locale) VALUES(2003, 'en')"; + +#Widget features + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(1,2000, 'first_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(2,2000, 'second_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(3,2000, 'third_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(8,2000, 'fourth_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(9,2000, 'fifth_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(4,2001, 'first_2001', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(5,2001, 'second_2001', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(6,2001, 'third_2001', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(7,2001, 'fourth_2001', 0)"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_ICONS} VALUES(2000, 'icon_src_2000', 50, 50)"; + sqlite3 $WRT_DB "insert into WidgetIcon(app_id, icon_src) VALUES(2002, 'icon_src_2002')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_ICONS} VALUES(2000, 1, 'en')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2000, 'start_file_2000')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2001, 'start_file_2001')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2002, 'start_file_2002')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2003, 'start_file_2003')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2000, 1, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2001, 2, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2002, 3, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2003, 4, 'en', '', '')"; + + #widget properties + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2000, 'tid2000', 'key1_for_2000', 'value_for_key1_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2000, 'tid2000', 'key2_for_2000', 'value_for_key2_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2001, 'tid2001', 'key1_for_2001', 'value1_for_key_2001', 1)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2002, 'tid2002', 'key1_for_2002', 'value1_for_key_2002', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2002, 'tid2002', 'key2_for_2002', 'value2_for_key_2002', 1)"; + + + exit $? + +elif [ "x$1" == "xstop" ]; then + echo stop; + cp $WRT_DB_BCK $WRT_DB + exit $? +else + exit 1 +fi diff --git a/uncrustify.cfg b/uncrustify.cfg new file mode 100644 index 0000000..2bf1d96 --- /dev/null +++ b/uncrustify.cfg @@ -0,0 +1,170 @@ +indent_align_string=true +indent_braces=false +indent_braces_no_func=false +indent_brace_parent=false +indent_namespace=false +indent_extern=false +indent_class=true +indent_class_colon=false +indent_else_if=false +indent_func_call_param=false +indent_func_def_param=false +indent_func_proto_param=false +indent_func_class_param=false +indent_func_ctor_var_param=false +indent_template_param=false +indent_func_param_double=false +indent_relative_single_line_comments=false +indent_col1_comment=true +indent_access_spec_body=false +indent_paren_nl=false +indent_comma_paren=false +indent_bool_paren=false +indent_square_nl=false +indent_preserve_sql=false +indent_align_assign=false +sp_balance_nested_parens=false +align_keep_tabs=false +align_with_tabs=false +align_on_tabstop=false +align_number_left=false +align_func_params=false +align_same_func_call_params=false +align_var_def_colon=false +align_var_def_attribute=false +align_var_def_inline=false +align_right_cmt_mix=false +align_on_operator=false +align_mix_var_proto=false +align_single_line_func=false +align_single_line_brace=false +align_nl_cont=false +align_left_shift=true +nl_collapse_empty_body=true +nl_assign_leave_one_liners=false +nl_class_leave_one_liners=false +nl_enum_leave_one_liners=false +nl_getset_leave_one_liners=false +nl_func_leave_one_liners=false +nl_if_leave_one_liners=false +nl_multi_line_cond=true +nl_multi_line_define=false +nl_before_case=false +nl_after_case=false +nl_after_return=false +nl_after_semicolon=true +nl_after_brace_open=false +nl_after_brace_open_cmt=false +nl_after_vbrace_open=false +nl_after_brace_close=false +nl_define_macro=false +nl_squeeze_ifdef=false +nl_ds_struct_enum_cmt=false +nl_ds_struct_enum_close_brace=false +nl_create_if_one_liner=false +nl_create_for_one_liner=false +nl_create_while_one_liner=false +ls_for_split_full=true +ls_func_split_full=true +nl_after_multiline_comment=false +eat_blanks_after_open_brace=true +eat_blanks_before_close_brace=true +mod_pawn_semicolon=false +mod_full_paren_if_bool=false +mod_remove_extra_semicolon=true +mod_sort_import=false +mod_sort_using=false +mod_sort_include=false +mod_move_case_break=false +mod_remove_empty_return=false +cmt_indent_multi=true +cmt_c_group=false +cmt_c_nl_start=false +cmt_c_nl_end=false +cmt_cpp_group=false +cmt_cpp_nl_start=false +cmt_cpp_nl_end=false +cmt_cpp_to_c=false +cmt_star_cont=true +cmt_multi_check_last=true +cmt_insert_before_preproc=false +pp_indent_at_level=false +pp_region_indent_code=false +pp_if_indent_code=false +pp_define_at_level=false +indent_columns=4 +indent_member=4 +indent_access_spec=-2 +code_width=80 +nl_max=2 +nl_before_access_spec=2 +cmt_width=80 +indent_with_tabs=0 +sp_arith=force +sp_assign=force +sp_enum_assign=force +sp_pp_concat=remove +sp_pp_stringify=remove +sp_bool=force +sp_compare=force +sp_paren_brace=force +sp_angle_paren=remove +sp_before_sparen=force +sp_inside_sparen=remove +sp_after_sparen=force +sp_sparen_brace=force +sp_before_semi=remove +sp_after_semi_for_empty=remove +sp_before_square=remove +sp_before_squares=remove +sp_inside_square=remove +sp_after_comma=force +sp_before_comma=remove +sp_after_class_colon=force +sp_before_class_colon=force +sp_before_case_colon=remove +sp_inside_braces=add +sp_inside_fparens=remove +sp_inside_fparen=remove +sp_func_call_paren=remove +sp_func_class_paren=remove +sp_else_brace=force +sp_brace_else=force +sp_catch_brace=force +sp_brace_catch=force +sp_try_brace=force +sp_before_dc=remove +sp_after_dc=remove +sp_not=remove +sp_inv=remove +sp_addr=remove +sp_member=remove +sp_deref=remove +sp_sign=remove +sp_incdec=remove +sp_cond_colon=force +sp_cond_question=force +sp_case_label=force +nl_assign_brace=remove +nl_if_brace=remove +nl_brace_else=remove +nl_elseif_brace=remove +nl_else_brace=remove +nl_else_if=remove +nl_try_brace=remove +nl_for_brace=remove +nl_catch_brace=remove +nl_brace_catch=remove +nl_while_brace=remove +nl_do_brace=remove +nl_brace_while=remove +nl_switch_brace=remove +nl_namespace_brace=remove +nl_class_brace=force +nl_fdef_brace=force +pos_class_comma=trail +pos_class_colon=trail +mod_full_brace_do=add +mod_full_brace_for=add +mod_full_brace_if=add +mod_full_brace_while=add diff --git a/uncrustify.sh b/uncrustify.sh new file mode 100755 index 0000000..49ad3cf --- /dev/null +++ b/uncrustify.sh @@ -0,0 +1 @@ +uncrustify -c uncrustify.cfg --no-backup `find . -regex "\(.*\.cpp\|.*\.h\|.*\.c\|.*\.cc\)" | grep -v "orm.h\|orm_generator.h\|3rdparty\|examples"` diff --git a/wrt-plugins-common.manifest b/wrt-plugins-common.manifest new file mode 100644 index 0000000..4ae6e9b --- /dev/null +++ b/wrt-plugins-common.manifest @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/wrt-plugins-common.map b/wrt-plugins-common.map new file mode 100644 index 0000000..29c429e --- /dev/null +++ b/wrt-plugins-common.map @@ -0,0 +1,6 @@ +{ + global: *; + local: *; +}; + + diff --git a/wrt-popup-ace-runtime.mobile.rule b/wrt-popup-ace-runtime.mobile.rule new file mode 100644 index 0000000..af50ad6 --- /dev/null +++ b/wrt-popup-ace-runtime.mobile.rule @@ -0,0 +1,14 @@ +wrt-popup-ace-runtime system::homedir rwx +wrt-popup-ace-runtime device::app_logging w +wrt-popup-ace-runtime ail::db rw +wrt-popup-ace-runtime xorg rwx +wrt-popup-ace-runtime isf rx +wrt-popup-ace-runtime system::vconf rwx +wrt-popup-ace-runtime sound_server rw +wrt-popup-ace-runtime e17 rw +e17 wrt-popup-ace-runtime rw +wrt-popup-ace-runtime system::share rwx +wrt-popup-ace-runtime pulseaudio rwx +wrt-popup-ace-runtime mobileprint x +wrt-popup-ace-runtime dbus r + diff --git a/wrt-popup-ace-runtime.mobile2.rule b/wrt-popup-ace-runtime.mobile2.rule new file mode 100644 index 0000000..105b2d3 --- /dev/null +++ b/wrt-popup-ace-runtime.mobile2.rule @@ -0,0 +1,13 @@ +wrt-popup-ace-runtime system::homedir rwx-- +wrt-popup-ace-runtime device::app_logging -w--- +wrt-popup-ace-runtime ail::db rw--- +wrt-popup-ace-runtime xorg rwx-- +wrt-popup-ace-runtime isf r-x-- +wrt-popup-ace-runtime system::vconf rwx-- +wrt-popup-ace-runtime sound_server rw--- +wrt-popup-ace-runtime e17 rw--- +e17 wrt-popup-ace-runtime rw--- +wrt-popup-ace-runtime system::share rwx-- +wrt-popup-ace-runtime pulseaudio rwx-- +wrt-popup-ace-runtime mobileprint --x-- +wrt-popup-ace-runtime dbus r---- diff --git a/wrt-popup-ace-runtime.rule b/wrt-popup-ace-runtime.rule new file mode 100644 index 0000000..f01a5bc --- /dev/null +++ b/wrt-popup-ace-runtime.rule @@ -0,0 +1,13 @@ +wrt-popup-ace-runtime system::homedir rwx +wrt-popup-ace-runtime device::app_logging w +wrt-popup-ace-runtime ail::db rw +wrt-popup-ace-runtime xorg rwx +wrt-popup-ace-runtime isf rx +wrt-popup-ace-runtime system::vconf rwx +wrt-popup-ace-runtime sound_server rw +wrt-popup-ace-runtime e17 rw +e17 wrt-popup-ace-runtime rw +wrt-popup-ace-runtime system::share rwx +wrt-popup-ace-runtime pulseaudio rwx +wrt-popup-ace-runtime dbus r + diff --git a/wrt-popup-wrt-runtime.mobile.rule b/wrt-popup-wrt-runtime.mobile.rule new file mode 100644 index 0000000..1ad6fbc --- /dev/null +++ b/wrt-popup-wrt-runtime.mobile.rule @@ -0,0 +1,14 @@ +wrt-popup-wrt-runtime system::homedir rwx +wrt-popup-wrt-runtime device::app_logging w +wrt-popup-wrt-runtime ail::db rw +wrt-popup-wrt-runtime xorg rwx +wrt-popup-wrt-runtime isf rx +wrt-popup-wrt-runtime system::vconf rwx +wrt-popup-wrt-runtime sound_server rw +wrt-popup-wrt-runtime e17 rw +e17 wrt-popup-wrt-runtime rw +wrt-popup-wrt-runtime system::share rwx +wrt-popup-wrt-runtime pulseaudio rwx +wrt-popup-wrt-runtime mobileprint x +wrt-popup-wrt-runtime dbus r + diff --git a/wrt-popup-wrt-runtime.mobile2.rule b/wrt-popup-wrt-runtime.mobile2.rule new file mode 100644 index 0000000..09a1e0a --- /dev/null +++ b/wrt-popup-wrt-runtime.mobile2.rule @@ -0,0 +1,13 @@ +wrt-popup-wrt-runtime system::homedir rwx-- +wrt-popup-wrt-runtime device::app_logging -w--- +wrt-popup-wrt-runtime ail::db rw--- +wrt-popup-wrt-runtime xorg rwx-- +wrt-popup-wrt-runtime isf r-x-- +wrt-popup-wrt-runtime system::vconf rwx-- +wrt-popup-wrt-runtime sound_server rw--- +wrt-popup-wrt-runtime e17 rw--- +e17 wrt-popup-wrt-runtime rw--- +wrt-popup-wrt-runtime system::share rwx-- +wrt-popup-wrt-runtime pulseaudio rwx-- +wrt-popup-wrt-runtime mobileprint --x-- +wrt-popup-wrt-runtime dbus r---- diff --git a/wrt-popup-wrt-runtime.rule b/wrt-popup-wrt-runtime.rule new file mode 100644 index 0000000..53211ca --- /dev/null +++ b/wrt-popup-wrt-runtime.rule @@ -0,0 +1,13 @@ +wrt-popup-wrt-runtime system::homedir rwx +wrt-popup-wrt-runtime device::app_logging w +wrt-popup-wrt-runtime ail::db rw +wrt-popup-wrt-runtime xorg rwx +wrt-popup-wrt-runtime isf rx +wrt-popup-wrt-runtime system::vconf rwx +wrt-popup-wrt-runtime sound_server rw +wrt-popup-wrt-runtime e17 rw +e17 wrt-popup-wrt-runtime rw +wrt-popup-wrt-runtime system::share rwx +wrt-popup-wrt-runtime pulseaudio rwx +wrt-popup-wrt-runtime dbus r + -- 2.7.4